Где найти и какие файлы хранятся в журнале apache и php

Содержание
  1. Introduction
  2. httpd -V
  3. Установка Apache
  4. Автозагрузка Apache
  5. Управление сервисом Apache
  6. Проверка состояния Apache
  7. Создание корневого каталога для статического сайта
  8. Создание корневого каталога для динамических файлов
  9. Изменение конфигурации
  10. Включение и отключение конфигурационных файлов
  11. Виртуальные хосты
  12. Модули
  13. Конфигурационные файлы
  14. Тестирование конфигурации
  15. Важные файлы и каталоги Apache
  16. Контент
  17. Конфигурация сервера
  18. Логи
  19. Заключение
  20. Уровни логирования
  21. Где находятся логи Apache?
  22. Общесерверные настройки логирования
  23. Логирование виртуальных хостов
  24. Пользовательские логи
  25. Ротация логов Apache
  26. Ротация логов вручную
  27. Утилита logrotate
  28. Ротация логов по каналам
  29. Заключение
  30. Команды systemctl для Apache
  31. Команды journalctl для Apache
  32. Устранение неполадок с помощью apachectl
  33. Логи Apache
  34. Заключение
  35. Step 3 — Viewing Apache Logs
  36. Step 1 — Getting To Know Apache Log Types
  37. Step 2 — Locating Apache Log Files
  38. Location Of The Access Log
  39. Location Of The Error Log
  40. Prerequisites
  41. What Is the Apache Error Log?
  42. Apache Errors Logs Location
  43. Apache Error Log Format Configuration
  44. Log Levels
  45. How to View Apache Error Logs
  46. Apache Log File Management and Analysis with Sematext
  47. Step 4 — Configuring Apache Access Logs
  48. Log Formats
  49. Common Log Format
  50. Combined Log Format
  51. Custom Log Format
  52. What Are Apache Logs?
  53. What Is the Apache Access Log?
  54. Apache Access Logs Location
  55. Apache Access Log Format Configuration
  56. Common Log Format
  57. Combined Log Format
  58. Custom Log Format
  59. Multiple Access Logs
  60. Conditional Logs
  61. Logs Rotation and Piped Logs
  62. How to Read Apache Access Logs
  63. Understanding Apache Access Logs
  64. Step 5 — Configuring Apache Error Logs
  65. Conclusion
  66. Conclusion

Introduction

In this tutorial, you will learn everything you need to know about Apache logging to help you troubleshoot and quickly resolve any problem you may encounter on your server. Logging is a very powerful tool that will give you valuable data about all the operations of your servers. You will learn where logs are stored, how to access them, and how to customize log output to fit your needs.

Apache – the technology that powers the web. I’m not sure if that is correct, but I think that we wouldn’t see the world wide web in its current shape without it. Launched in 1995 and since April 1996, it has been the most popular web server around the world.

I’ve installed Apache, PHP, and MySQL on Ubuntu 10.10 desktop edition, and it’s working fine.
Except I have no clue where to look for Apache or PHP log files.

kiri's user avatar

16 gold badges79 silver badges117 bronze badges

asked Nov 24, 2010 at 18:58

Stann's user avatar

By default, /var/log/apache2/error.log.

This can be configured in /etc/php5/apache2/php.ini.

Community's user avatar

answered Nov 24, 2010 at 19:18

misterben's user avatar

3 gold badges22 silver badges27 bronze badges

Check these settings in php.ini:

  1. error_reporting = E_ALL | E_STRICT (as recommended for development in php.ini)
  2. error_log = /var/log/php_errors.log
  3. Then create log file manually

    touch /var/log/php_errors.log
    chown www-data: /var/log/php_errors.log
    chmod +rw /var/log/php_errors.log

Now you can view PHP errors by this way

tail /var/log/php_errors.log

This is an agreeable solution to this issue for me.

Community's user avatar

answered Sep 7, 2012 at 23:13

Nikolay Chuprina's user avatar

ErrorLog ${APACHE_LOG_DIR}/[your-vhost]-error.log

That might be useful if you have a lot of vhosts and want to split where they report the errors.

sudo tail -f /var/log/apache2/error.log

This is particularly useful when doing live debugging.

Eliah Kagan's user avatar

54 gold badges312 silver badges488 bronze badges

answered Jun 3, 2012 at 21:52

ywarnier's user avatar

4 silver badges4 bronze badges

If Apache was setup with Webmin/Virtualmin there is a separate folder for each VirtualHost.

These are two files:

So they are

tail -f ~/logs/error_log

answered Apr 1, 2018 at 12:18

Ilyich's user avatar

3 bronze badges

If you use a bitnami distribution, it is at:

tail /opt/bitnami/apache2/logs/error_log

Bitnami distributions have their own directory structure. I had to find what it was for my server, and this is where it resides by default for bitnami. I would assume lots of people are looking for the same thing when using a bitnami distribution.

answered Oct 24, 2021 at 19:37

eyal_katz's user avatar

I need to find where Apache is keeping the access and error logs for a site.

I have root access to a server where dozens of sites are hosted. I’m trying to debug one of those sites. When I browse the site, it doesn’t show up on /var/logs/apache2/access.log or /var/logs/apache2/error.log. (The files are there, and other sites gets logged on those. In fact, there are hundreds of different log files).

Neither locate httpd.log nor find . -iname httpd.log performed at / issue any results.

The apache configuration for the site is:

ServerName REDACTED.com.br
DocumentRoot /var/www/xyz/wiki
AssignUserId xyz_wiki xyz_wiki
<Directory /var/www/xyz/wiki/data>
order allow,deny
deny from all
</Directory>
<Directory /var/www/xyz/wiki/conf>
order allow,deny
deny from all
</Directory>
<Directory /var/www/xyz/wiki/bin>
order allow,deny
deny from all
</Directory>
<Directory /var/www/xyz/wiki/inc>
order allow,deny
deny from all
</Directory>
php_admin_value open_basedir /var/www/xyz/wiki/:/mnt/vdImagem/www/xyz/wiki/

Community's user avatar

asked Feb 19, 2014 at 19:04

That Brazilian Guy's user avatar

You can inquire about his information from Apache’s log files but it’s generally better to inquire about these things from the actual executable. Parsing the logs can be tricky and you’ll likely make a mistake if you aren’t that familiar with how a particular setup was done on a box.

httpd -V

$ httpd -V
Server version: Apache/2.2.15 (Unix)
Server built: Feb 13 2012 22:31:42
Server's Module Magic Number: 20051115:24
Server loaded: APR 1.3.9, APR-Util 1.3.9
Compiled using: APR 1.3.9, APR-Util 1.3.9
Architecture: 64-bit
Server MPM: Prefork threaded: no forked: yes (variable process count)
Server compiled with.... -D APACHE_MPM_DIR="server/mpm/prefork" -D APR_HAS_SENDFILE -D APR_HAS_MMAP -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled) -D APR_USE_SYSVSEM_SERIALIZE -D APR_USE_PTHREAD_SERIALIZE -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT -D APR_HAS_OTHER_CHILD -D AP_HAVE_RELIABLE_PIPED_LOGS -D DYNAMIC_MODULE_LIMIT=128 -D HTTPD_ROOT="/etc/httpd" -D SUEXEC_BIN="/usr/sbin/suexec" -D DEFAULT_PIDLOG="run/httpd.pid" -D DEFAULT_SCOREBOARD="logs/apache_runtime_status" -D DEFAULT_LOCKFILE="logs/accept.lock" -D DEFAULT_ERRORLOG="logs/error_log" -D AP_TYPES_CONFIG_FILE="conf/mime.types" -D SERVER_CONFIG_FILE="conf/httpd.conf"
  1. This tells you the «root» directory that all the files Apache will reference start from:

     -D HTTPD_ROOT="/etc/httpd"
  2. config files are defined, starting here. Note that this path is relative to the path mentioned in #1, so it would be /etc/httpd/conf/httpd.conf.

     -D SERVER_CONFIG_FILE="conf/httpd.conf"
  3. Error log is here.

     -D DEFAULT_ERRORLOG="logs/error_log"

    NOTE: This one might be a bit confusing at first but on Red Hat distros there is a link that is often made in this directory, /etc/httpd called logs.

    $ ls -ld /etc/httpd/logs
    lrwxrwxrwx. 1 root root 19 Jul 9 2012 /etc/httpd/logs -> ../../var/log/httpd
  4. Other log files that might be utilized by Apache will be defined further in the config file, /etc/httpd/conf/httpd.conf.

answered Feb 19, 2014 at 20:22

slm's user avatar

I couldn’t get any of the command from the other answers to find my value. I ended up finding what i needed by running less /etc/apache2/envvars

answered Apr 15, 2021 at 15:10

Oxymoron's user avatar

1 silver badge3 bronze badges

Look in your apache config for the string ErrorLog.

Usually there’s one for the Apache process itself. Each VirtualHost can also define its own log files so check those as well.

If the VirtualHost doesn’t define its own log file then it will be using the one specified in the global configuration. If you think you’ve found the correct log file but you aren’t seeing the information you need then try increasing the LogLevel.

answered Feb 19, 2014 at 19:07

bahamat's user avatar

4 gold badges70 silver badges103 bronze badges

I just found a file /etc/apache2/conf.d/other-vhosts-access-log which contains

# Define an access log for VirtualHosts that don't define their own logfile
CustomLog ${APACHE_LOG_DIR}/other_vhosts_access.log vhost_combined

Looks like it is a way to combine all logs from vhosts in a single file. I have checked and the accesses were being recorded there.

Inserting an ErrorLog and an AccessLog directive on the config file for that site provided me separate log files.

answered Feb 19, 2014 at 20:10

That Brazilian Guy's user avatar





11 января, 2018 1:44 пп

Apache – это популярный веб-сервер с открытым исходным кодом, который отличается гибкостью, производительностью и широкой поддержкой. Данный мануал ознакомит вас с общими процедурами по поддержке Apache, включая управление сервисом, работу с виртуальными хостами и редактирование конфигураций.

Примечание: Мануал предназначен для пользователей, которые работают с Apache в Ubuntu. Если вы используете CentOS или другой дистрибутив RHEL, обратитесь к мануалу Установка LAMP stack на CentOS 7.

Каждый раздел может использоваться независимо от других, поэтому вы можете пропустить разделы, которые вам не нужны. Все условные значения в командах выделены красным; вместо этих значений вы можете подставить свои данные.

Каждый раздел предлагает ссылки на другие руководства, с которыми можно проконсультироваться.

Установка Apache

Чтобы установить сервис Apache, обновите индекс пакетов и запустите следующую команду:

sudo apt-get update
sudo apt-get install apache2

Автозагрузка Apache

Сервис Apache запускается автоматически. Если вы хотите изменить это поведение, введите:

sudo systemctl disable apache2.service

Чтобы снова добавить Apache в автозагрузку, введите:

sudo systemctl enable apache2.service

Управление сервисом Apache

Чтобы остановить сервер Apache, введите следующую команду:

sudo systemctl stop apache2

Чтобы запустить сервер Apache, введите:

sudo systemctl start apache2

Чтобы остановить сервис и запустить его снова, введите:

sudo systemctl restart apache2

Если вы изменили конфигурацию, вы можете перезагрузить Apache в текущей сессии. Введите следующую команду:

sudo systemctl reload apache2

Проверка состояния Apache

Чтобы проверить состояние Apache, введите команду:

sudo systemctl status apache2

Эта команда сообщит, работает ли Apache и покажет вам последние несколько строк логов.

Создание корневого каталога для статического сайта

При создании сайтов на Apache разработчики часто используют виртуальные хосты – это хосты, которые обслуживают отдельные сайты или домены. Для этого нужно создать document root, каталог верхнего уровня, который Apache проверяет при обслуживании контента.

sudo mkdir -p /var/www/example.com/public_html

Передайте права на каталог пользователю с доступом к sudo.

Предоставьте остальным пользователям права на чтение контента:

Помните, что права доступа должны меняться в соответствии с ситуацией.

Создание корневого каталога для динамических файлов

Если ваш сайт использует динамические модули типа PHP, создайте каталог document root для этих файлов:

sudo mkdir -p /var/www/example.com/public_html

Передайте права на каталог пользователю sudo и группе www-data:

sudo chown -R 8host:www-data /var/www/example.com/public_html

Изменение конфигурации

При работе с виртуальными хостами необходимо изменить параметры конфигурации и добавить данные о домене, чтобы сервер Apache мог правильно реагировать на запросы.

Откройте файл виртуального хоста:

sudo nano /etc/apache2/sites-available/example.com.conf

Измените следующие строки:

После изменения файл будет выглядеть так:

Прежде чем сохранить файл, убедитесь, что в директивах нет ошибок.

Включение и отключение конфигурационных файлов

Виртуальные хосты

Чтобы включить виртуальный хост, введите:

sudo a2ensite example.com.conf

Чтобы отключить конфигурационный файл (в данном примере это стандартный виртуальный хост):

sudo a2dissite 000-default.conf

Модули

Чтобы включить модули из каталога /etc/apache2/mods-available, введите:

sudo a2enmod example_mod

Чтобы отключить конкретный модуль:

sudo a2dismod example_mod

Конфигурационные файлы

Чтобы включить конфигурационные файлы из каталога /etc/apache2/conf-available (файлы, не связанные с виртуальными хостами), введите:

sudo a2enconf

Чтобы отключить файл, введите:

sudo a2disconf

Тестирование конфигурации

Каждый раз, когда вы вносите изменения в конфигурационные файлы Apache, обязательно выполните следующую команду, чтобы проверить наличие синтаксических ошибок:

sudo apache2ctl configtest

Важные файлы и каталоги Apache

Контент

Каталог /var/www/html хранит весь контент сайта (это корневой каталог сайта). Вы можете изменить стандартные настройки Apache и указать другие каталоги в var/www.

Конфигурация сервера

  • /etc/apache2: конфигурационный каталог Apache (здесь хранятся все конфигурационные файлы веб-сервера).
  • /etc/apache2/apache2.conf: главный конфигурационный файл веб-сервера, в котором находятся все глобальные параметры. Все остальные файлы загружаются через этот файл. Также тут хранятся директивы FollowSymLinks, которые отвечают за включение и отключение конфигурационных файлов.
  • /etc/apache2/sites-available/: здесь находятся все виртуальные хосты (в том числе и отключенные). В этом каталоге происходят все изменения в настройке виртуального хоста. Эти файлы включаются с помощью команды a2ensite.
  • /etc/apache2/sites-enabled/: здесь хранятся файлы включенных виртуальных хостов. При запуске или перезагрузке Apache читает конфигурационные файлы и ссылки в этом каталоге, чтобы собрать полную конфигурацию.
  • /etc/apache2/conf-available и /etc/apache2/conf-enabled: работают по тому же принципу, что и sites-available и sites-enabled. Эти каталоги предназначены для хранения фрагментов конфигурации, которые не входят в виртуальные хосты.
  • /etc/apache2/mods-available и /etc/apache2/mods-enabled: эти каталоги работают аналогичным образом. Они предназначены для хранения модулей. В них находятся файлы двух типов: файлы с расширением .load загружают модули, а файлы .conf хранят их конфигурации.
Читайте также:  Объяснение индексов MySQL: типы, преимущества и сценарии использования

Логи

  • /var/log/apache2/access.log – это лог, который регистрирует все запросы Apache (если в конфигурации веб-сервера не сказано другого).
  • /var/log/apache2/error.log – это лог ошибок. Настроить уровень логирования можно с помощью параметра LogLevel в /etc/apache2/apache2.conf.

Другой способ доступа к информации о компонентах Apache – через journald. Этот инструмент собирает информацию логов приложений и ядра. Чтобы просмотреть записи для модуля Apache, введите:

sudo journalctl -u apache2

Заключение

Tags: Apache






25 ноября, 2015 11:53 дп

Веб-сервер Apache может предоставлять администратору много полезной информации о своей работе, а также о проблемах и ошибках, которые нужно устранить.

Вовремя настроенное журналирование позволяет в дальнейшем избежать неожиданных проблем с веб-сервером. Информация, хранящаяся в логах (или журналах) сервера, помогает быстро оценить ситуацию и устранить ошибки. Apache предоставляет очень гибкий механизм журналирования.

Данное руководство знакомит с возможностями журналирования Apache и предназначенными для этого инструментами.

Примечание: В данном руководстве используется Apache2 на сервере Ubuntu 12.04, но инструкции подойдут и для других дистрибутивов.

Уровни логирования

Apache делит все уведомляющие сообщения на категории в зависимости от важности соощения.

Для этого существуют уровни логирования. К примеру, наиболее важные сообщения, уведомляющие о критических ошибках и сбоях, существует уровень emerg. А сообщения уровня info просто предоставляют полезные подсказки.

Существуют следующие уровни логирования:

  • emerg: критическая ситуация, аварийный сбой, система находится в нерабочем состоянии.
  • alert: сложная предаварийная ситуация, необходимо срочно принять меры.
  • crit: критические проблемы, которые необходимо решить.
  • error: произошла ошибка.
  • warn: предупреждение; в системе что-то произошло, но причин для беспокойства нет.
  • notice: система в норме, но стоит обратить внимание на её состояние.
  • info: важная информация, которую следует принять к сведению.
  • Debug: информация для отладки, которая может помочь определить проблему.
  • trace[1-8]: Трассировка информации различных уровней детализации.

При настройке логирования задаётся наименее важный уровень, который нужно вносить в лог. Что это значит? Логи фиксируют указанный уровень логирования, а также все уровни с более высоким приоритетом. К примеру, если выбрать уровень error, логи будут фиксировать уровни error, crit, alert и emerg.

Для настройки уровня логирования существует директива LogLevel. Уровень логирования по умолчанию задан в стандартном конфигурационном файле:

sudo nano /etc/apache2/apache2.conf
. . .
LogLevel warn
. . .

Как видите, по умолчанию Apache вносит в лог сообщения уровня warn (и более приоритетных уровней).

Где находятся логи Apache?

Apache может разместить свои логи, используя общесерверные настройки ведения логов. Также можно настроить индивидуальное логирование для каждого отдельного виртуального хоста.

Общесерверные настройки логирования

Чтобы узнать, где находятся стандартные логи сервера, откройте конфигурационный файл. В Ubuntu это /etc/apache2/apache2.conf:

sudo nano /etc/apache2/apache2.conf

Найдите в файле строку:

Данная директива указывает на расположение лога, в котором Apache хранит сообщения об ошибках. Как видите, для получения префикса пути к каталогу используется переменная среды APACHE_LOG_DIR.

Чтобы узнать значение переменной APACHE_LOG_DIR, откройте файл envvars:

sudo nano /etc/apache2/envvars
. . .
export APACHE_LOG_DIR=/var/log/apache2$SUFFIX
. . .

Согласно этому файлу, переменная APACHE_LOG_DIR настроена на каталог /var/log/apache2. Это означает, что Apache  соединит это значение с директивой в конфигурационном файле apache2.conf и будет вносить данные в лог /var/log/apache2/error.log.

sudo ls /var/log/apache2
access.log  error.log  other_vhosts_access.log

Как видите, тут находится лог ошибок error.log и несколько других логов.

Логирование виртуальных хостов

Файл access.log, упомянутый в конце предыдущего раздела, не настраивается в файле apache2.conf. Вместо этого разработчики поместили соответствующую директиву в файл виртуального хоста.

Откройте и просмотрите стандартный виртуальный хост:

sudo nano /etc/apache2/sites-available/default

Пролистайте файл и найдите следующие три значения, связанные с логированием:

Местонахождение ErrorLog совпадает с его определением в стандартном конфигурационном файле. Эта строка не обязательно должна находиться в двух отдельных файлах; при изменении местонахождения этого лога в одном из файлов ошибки не возникнет.

Пользовательские логи

В предыдущем разделе строка, описывающая access.log, использует не такую директиву, как предыдущие строки для настройки логов. Она использует CustomLog:

Эта директива имеет такой синтаксис:

CustomLog log_location log_format

В данном случае log_format (формат логов) является комбинированным (combined). Эта спецификация не является внутренней спецификацией Apache; она задаёт пользовательский формат, который определен в конфигурационном файле по умолчанию.

Снова откройте конфигурационный файл по умолчанию и найдите строку, определяющую формат combined:

Команда LogFormat определяет пользовательский формат логов, вызываемых директивой CustomLog.

Этот формат называется комбинированным (combined).

Примечание: Подробнее о доступных форматах можно узнать здесь.

Существует еще несколько распространённых форматов, которые можно использовать в определении виртуальных хостов. Можно также создавать свои собственные форматы.

Ротация логов Apache

Ротация логов – это процесс, подразумевающий отключение устаревших или слишком объёмных лог-файлов и их архивирование (на установленный период времени). Apache может вносит в лог довольно большие объёмы данных, следовательно, во избежание заполнения дискового пространства необходимо настроить ротацию логов.

Ротация логов может быть очень простой (как, например, отключение слишком больших логов), а может иметь и более сложную конфигурацию (то есть, функционировать как система архивирования и хранения старых логов).

Рассмотрим методы настройки ротации логов Apache.

Ротация логов вручную

Перемещать логи во время работы Apache нельзя. То есть, чтобы переместить в архив устаревшие или заполненные логи и заменить их новыми, нужно перезапустить сервер.

Это можно сделать вручную. Для этого нужно переместить устаревшие файлы, а затем, перезапустив Apache, обновить настройки веб-сервера и заставить его использовать новые логи.

Ниже приведён пример из документации Apache. Возможно, понадобится добавить в начало этих команд sudo.

Эти команды переместят файлы, перезапустят сервер и скажут ему подождать 600 секунд. Таким образом Apache сможет использовать старые лог-файлы, чтобы завершить регистрацию старых запросов. В течение этого времени новые запросы будут записаны в новые лог-файлы.

Имейте в виду: ротация логов вручную очень ненадёжна в больших серверных средах.

Утилита logrotate

По умолчанию система Ubuntu настраивает ротацию логов при помощи утилиты logrotate.

Данная программа может выполнять ротацию логов при соблюдении определенных критериев. Просмотреть события, включающие Logrotate для ротации логов, можно в файле /etc/logrotate.d/apache2:

sudo nano /etc/logrotate.d/apache2

В нём находится несколько параметров logrotate. Обратите внимание на первую строку:

Это значит, что logrotate будет выполнять ротацию только тех логов, которые находятся в /var/log/apache2. Имейте это в виду, если вы выбрали другой каталог для хранения в конфигурации Apache.

Как видите, логи ротируются еженедельно. Также тут есть раздел кода, перезапускающий Apache после ротации:

postrotate
/etc/init.d/apache2 reload > /dev/null
endscript

Эти строки автоматически перезапускают веб-сервер Apache после завершения ротации.

Примечание: К сожалению, настройки данного файла не охвачены в данном руководстве.

Ротация логов по каналам

Использование каналов вместо файлов – простой способ передать обработку вывода программе логирования.  Это также решает проблему ротации логов, поскольку ротация может выполняться с помощью программы на серверной стороне (а не самим сервером Apache).

Чтобы логи обрабатывались программой логирования, принимающей стандартный вывод, замените следующую строку следующим образом:

Apache запустит программу логирования во время загрузки и перезапустит её в случае ошибки или сбоя.

Для ротации логов можно использовать разные программы, но по умолчанию Apache поставляется с rotatelogs. Чтобы настроить эту программу, используйте:

Аналогичную конфигурацию можно создать и для других программ.

Заключение

Конечно, это руководство охватывает только основы логирования Apache.

Правильная настройка механизмов логирования и разумное управление лог-файлами сэкономят немало времени и сил в случае возникновения проблем с сервером. Имея быстрый доступ к информации, которая поможет определить проблемы, можно в кратчайшие сроки исправить все ошибки.

Также очень важно следить за логами сервера, чтобы случайно не подвергнуть опасности конфиденциальную информацию.

Tags: Apache, Apache 2, Logrotate, Ubuntu 12.04






8 сентября, 2020 11:28 дп

Centos, Debian, LAMP Stack, Ubuntu

Эта серия мануалов поможет вам предотвратить или устранить самые распространенные ошибки, которые возникают при работе с веб-сервером Apache.

Каждый последующий мануал в этой серии включает описание распространенных ошибок Apache, связанных с конфигурацией, сетью, файловой системой или привилегиями. Мы начнем с обзора команд и логов, которые вы можете использовать для устранения неполадок Apache. В последующих руководствах мы подробно рассмотрим конкретные ошибки.

Есть три основные команды и несколько общих логов, которые вы можете использовать, чтобы начать устранение ошибок Apache. По сути здесь вы найдете стандартную стратегию поиска ошибок и их причин: обычно эти команды используются в указанном здесь порядке, после чего можно изучить логи на предмет конкретных диагностических данных.

Команды, которые необходимы для устранения неполадок Apache в большинстве дистрибутивов Linux:

  • systemctl – используется для управления сервисами Linux и взаимодействия с ними через менеджер сервисов systemd.
  • journalctl – используется для запроса и просмотра логов, созданных systemd.
  • apachectl – при устранении неполадок эта команда используется для проверки конфигурации Apache.

Далее мы подробно опишем эти команды, способы их использования и расположение логов Apache, в которых можно найти дополнительную информацию об ошибках.

Примечание: В системах Debian и Ubuntu сервис и процесс Apache называется apache2, а в CentOS, Fedora и других системах RedHat – httpd. Имя сервиса и процесса – это единственное отличие команд запуска, остановки и проверки состояния Apache в разных системах. Логи journalctl также должны работать одинаково в любой системе Linux, которая использует systemd для управления Apache. При работе с этим мануалом вы должны использовать правильное имя сервиса в зависимости от вашего дистрибутива Linux.

Команды systemctl для Apache

В Ubuntu и Debian используйте:

sudo systemctl status apache2.service -l --no-pager

Флаг -l отображает полный вывод без сокращения. Флаг –no-pager направляет вывод непосредственно на ваш терминал. Вы должны получить такой результат:

apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: active (running) since Mon 2020-07-13 14:43:35 UTC; 1 day 4h ago
Process: 929 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
Main PID: 1346 (apache2)
Tasks: 55 (limit: 4702)
CGroup: /system.slice/apache2.service
├─1346 /usr/sbin/apache2 -k start
. . .

Чтобы изучить процесс веб-сервера в CentOS и Fedora, используйте:

sudo systemctl status httpd.service -l --no-pager

Вы получите такой результат:

Независимо от дистрибутива вы должны обратить внимание на строку Active в выводе. Если ваш сервер Apache не отображается как active (running), хотя он должен работать, возможно, произошла ошибка и прервала его работу. Как правило, при возникновении ошибок в выводе будет строка failed:

Active: failed (Result: exit-code) since Tue 2020-07-14 20:01:29 UTC; 1s ago

Если проблема заключается в процессе или конфигурации Apache, вы можете устранить ее с помощью команды journalctl.

Команды journalctl для Apache

Чтобы проверить логи systemd для Apache, вы можете использовать команду journalctl. Логи systemd для Apache обычно содержат данные о проблемах с запуском или управлением процессом Apache.

Эти логи отделены от логов запросов и ошибок Apache. Команда journalctl отображает логи systemd, которые описывают сам сервис Apache (от его запуска до завершения работы, включая все ошибки процесса, которые могут возникнуть на этом пути).

В системах Ubuntu и Debian для проверки логов используйте следующую команду:

sudo journalctl -u apache2.service --since today --no-pager

Флаг –since today ограничивает вывод команды записями лога, начиная с 00:00:00 текущего дня. Использование этой опции поможет ограничить объем записей лога, которые вам необходимо изучить для выявления ошибок. Вы должны получить следующий результат:

Если вы используете систему на базе CentOS или Fedora, введите эту версию команды:

sudo journalctl -u httpd.service --since today --no-pager

Вы получите такой результат:

В случае ошибки в выводе будет строка, приведенная ниже (имя хоста будет отличаться в зависимости от дистрибутива Linux):

Если в ваших логах Apache есть подобные ошибки, то следующее, что нужно сделать для устранения возможных проблем – это исследовать конфигурации Apache с помощью инструмента командной строки apachectl.

Устранение неполадок с помощью apachectl

Большинство дистрибутивов Linux включают утилиту apachectl в установку Apache по умолчанию. apachectl – бесценный инструмент, помогающий обнаруживать и диагностировать проблемы конфигурации Apache.

Читайте также:  Создать панель инструментов для визуализации журналов приложений в Kibana

Проверьте конфигурацию Apache с помощью команды apachectl configtest. Инструмент проанализирует ваши файлы Apache и обнаружит все ошибки или недостающие настройки перед попыткой запуска сервера.

Команда одинакова для дистрибутивов Ubuntu, Debian, CentOS и Fedora:

sudo apachectl configtest

Если конфигурация Apache не содержит ошибок, вы получите такой результат:

В зависимости от вашего дистрибутива Linux в выводе могут быть и другие строки, но самая важная строка – это та, в которой говорится, что с синтаксисом все ок.

Если в вашей конфигурации Apache есть ошибка (например, директива ссылается на деактивированный модуль) или опечатка, apachectl обнаружит ее и попытается уведомить вас о проблеме.

Например, попытка использовать в директиве отключенный модуль Apache приведет к появлению следующих сообщений apachectl:

AH00526: Syntax error on line 232 of /etc/apache2/apache2.conf:
Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.

В этом примере модуль ssl не включен, поэтому при проверке конфигурации директива SSLEngine выдает ошибку. Последняя строка также указывает, что в логе ошибок Apache может содержаться дополнительная информация, и это следующее место для поиска подробной отладочной информации.

Логи Apache

Логи Apache – очень полезный ресурс для устранения неполадок. Как правило, каждая ошибка, возникающая в браузере или другом HTTP-клиенте, создает соответствующую запись в логах Apache. Иногда Apache также выводит в свои логи ошибки, связанные с конфигурацией, встроенными модулями и другой отладочной информацией.

Чтобы проверить ошибки при устранении неполадок Apache на сервере Fedora, CentOS или RedHat, изучите файл /var/log/httpd/error_log.

Если вы устраняете неполадки в системе Debian или Ubuntu, проверьте /var/log/apache2/error.log с помощью инструмента tail или less. Например, чтобы просмотреть последние две строки лога ошибок с помощью tail, выполните следующую команду:

sudo tail -n 2 /var/log/apache2/error.log

Замените количество строк, которые вы хотите изучить. Укажите количество строк вместо числа 2 в команде.

В системе CentOS или Fedora файл журнала для проверки – /var/log/httpd/error_log.

Ниже мы приводим пример пример ошибки (ее текст не зависит от дистрибутива Linux):

Эти две строки представляют собой отдельные сообщения об ошибках. Обе они ссылаются на модуль, вызвавший ошибку (proxy в первой строке, proxy_http во второй), и содержат код ошибки, индивидуальный для модуля. Первый, AH00957, указывает на то, что сервер Apache пытался подключиться к бэкенд-серверу (в данном случае к 127.0.0.1 по порту 9090) с помощью модуля proxy, но не смог этого сделать.

Вторая ошибка исходит из первой: AH01114 – это ошибка модуля proxy_http, которая также указывает на то, что Apache не смог подключиться к бэкенд-серверу для выполнения HTTP-запроса.

Эти строки мы привели просто для примера. Если вы диагностируете ошибки на своем сервере Apache, скорее всего, вы найдете совсем другие строки с ошибками в ваших логах. Независимо от дистрибутива Linux, строки ошибок в логах всегда содержат соответствующий модуль Apache и код ошибки, а также текстовое описание ошибки.

Как только вы поймете, что могло вызвать вызывать проблему на вашем сервере Apache, вы можете продолжить исследование и устранение неполадок. Код ошибки и текстовое описание особенно полезны, поскольку дают конкретные указания, которые можно использовать для сужения диапазона возможных причин возникновения ошибки.

Заключение

Устранение ошибок Apache может включать как диагностику ошибок сервиса, так и обнаружение неверно настроенных параметров модулей. В этом вводном руководстве по диагностике Apache мы посмотрели, как использовать ряд утилит, чтобы сузить круг возможных причин появления ошибок. Обычно эти утилиты нужно использовать в том же порядке, в каком они описаны тут (но вы всегда можете пропустить некоторые действия или начать сразу с изучения логов, если у вас есть общее представление о том, в чем может быть проблема).

Однако чаще всего полезно следовать общей схеме устранения неполадок и использовать эти инструменты в описанном порядке. Начните с systemctl, чтобы проверить состояние сервера Apache. Если вам нужна дополнительная информация, изучите логи systemd для Apache с помощью команды journalctl. Если после проверки journalctl проблема все еще не ясна, проверьте конфигурации Apache с помощью команды apachectl configtest. Для более глубокого изучения неполадок проверьте логи Apache, обычно они указывают на конкретную ошибку (предоставляя полезные для диагностики данные и коды ошибок).

Tags: Apache, apachectl, journalctl, systemctl


Step 3 — Viewing Apache Logs

If you are working from an operating system with the UI, the easiest way to view stored logs is by opening files in the text editor. However, sometimes you need to view the content of the files directly in the terminal. In this case, there are few ways to do it.

You can tail command to view logs in real time:

tail -f /var/log/apache2/access.log

Enter fullscreen mode

Exit fullscreen mode

The tail command is used to print the last 10 lines from the selected file. With the -f option, the tail command will be viewing the content of the file in real-time.

To view the full content of the file, you can use the cat command:

cat /var/log/apache2/access.log

Enter fullscreen mode

Exit fullscreen mode

You may also want to find a specific term in the file. In that case, you can use the grep command:

grep GET /var/log/apache2/access.log

Enter fullscreen mode

Exit fullscreen mode

First, specify the term you want to search for, then specify the actual log file. In this case, we are looking for lines in the access log file where GET therm is present.

Step 1 — Getting To Know Apache Log Types

Apache writes logs of its events in two different log files.

Access Log — In this file, Apache stores information about incoming requests.

Error Log — This file contains information about errors that the web server encountered while processing requests.

Step 2 — Locating Apache Log Files

The location of the access log file is dependent upon the operating system on which is Apache web server running.



Location Of The Access Log

On Debian-based operating systems like Ubuntu, the access log file is located /var/log/apache2/access.log

On CentOS, the access log file is stored in /var/log/httpd/access.log
A typical access log entry might look like this:

Output:
::1 - - [13/Nov/2020:11:32:22 +0100] "GET / HTTP/1.1" 200 327 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"

Enter fullscreen mode

Exit fullscreen mode



Location Of The Error Log

On Debian-based operating systems like Ubuntu, the access log file is located /var/log/apache2/error.log

On CentOS, the access log file is stored in /var/log/httpd/error.log
A typical error log entry might look like this:

Output:
[Thu May 06 12:03:28.470305 2021] [php7:error] [pid 731] [client ::1:51092] script '/var/www/html/missing.php' not found or unable to stat

Enter fullscreen mode

Exit fullscreen mode

Prerequisites

Apache web server.
Sudo privileges.

What Is the Apache Error Log?

So far, we’ve talked about the Apache access log that gives us information on the accessed resources. But it is not the only thing that we should be interested in. We should also care about everything related to errors. In fact, the error log is the most important log file for the Apache HTTP server.

The Apache error log is where all the errors that happened during the processing of the requests. The most important thing, though, is that the error log will contain information on what went wrong during the Apache server startup and it is very likely that it will also contain hints on how to fix the issue.

Apache Errors Logs Location

Where the Apache error log is stored differs depending on the operating system on which it is running.

  • On Red Hat, CentOS, or Fedora Linux, the access logs can be found in the /var/log/httpd/error_log by default.
  • On Debian and Ubuntu, you can expect to find the Apache logs in the /var/log/apache2/error.log
  • FreeBSD will have the Apache server access logs in /var/log/httpd-error.log file.

You can configure its location using the ErrorLog directive, for example:

ErrorLog "/var/log/httpd-error.log"

Apache Error Log Format Configuration

Similar to the Apache access log, you can adjust the format of the error log. The Apache error log format is configured by using the ErrorLogFormat element, for example:

[Wed Nov 10 10:21:23.811033 2021] [core:error] [pid 22308:tid 3212342123] [client 10.1.2.3] File does not exist: /usr/local/apache2/htdocs/favicon.ico
  • %{u}t – the current time including microseconds,
  • %-m – the module that produced the error,
  • %l – the level of the log event,
  • %P – process identifier,
  • %T – thread identifier,
  • %M – the actual log message.

The full description of the available formatting options is available in the official Apache Server documentation.

Log Levels

LogLevel info rewrite:error
  • emerg
  • alert
  • crit
  • error
  • warn
  • notice
  • info
  • debug
  • trace1 – trace8

The emerg one is the log event that says that the system is unstable and the trace levels are used for very low-level information logging that you can probably skip.

How to View Apache Error Logs

Viewing the Apache server error logs is just as simple as opening the text file. The error logs are not different from the access logs, so they are just simple text files. You can use whatever tools you want to look into them. But keep in mind that looking into logs from multiple Apache servers distributed across multiple data centers can be challenging. That’s why we strongly suggest using log aggregation tools, such as Sematext Logs, for that job.

Apache Log File Management and Analysis with Sematext

apache log management tool

Sematext Cloud Logs – Apache Overview

Understanding and analyzing your Apache servers logs was never easier than with Sematext Logs. The only thing that you need to do is create an account with Sematext, create the Apache Logs App and install the Sematext Agent. You will be guided through the process of setting up the automatic Logs Discovery for your Logs. Your logs will be parsed and sent to the Sematext Logs giving you access to a variety of pre-built reports tailored for your Apache HTTP server.

apache logging

Sematext Logs – Apache HTTP Information

Still not sure which open-source search engine to use? Check out this quick video comparing Apache Solr and Elasticsearch below:

Step 4 — Configuring Apache Access Logs



Log Formats

As was mentioned earlier, logs are a powerful tool. To be able to use this tool you need to understand the format in which are logs stored. The format of the access logs and the log file location is defined in the CustomLog directive. This directive can be used in the server configuration file (/etc/apache2/apache2.conf) or your virtual host entry. Be aware that defining the same CustomLog directive in both files may cause problems.



Common Log Format

The common log format is the standardized text file format used by many web servers. It’s popular as it is easy to read and contains just the necessary information. Its defined in the /etc/apache2/apache2.conf configuration file and its format look like this:

LogFormat "%h %l %u %t \\"%r\\" %>s %O" common

Enter fullscreen mode

Exit fullscreen mode

The entry in the log file will look like this:

Output:
127.0.0.1 alice Alice [06/May/2021:11:26:42 +0200] "GET / HTTP/1.1" 200 3477
This is the information that the log message contains:

Enter fullscreen mode

Exit fullscreen mode



Combined Log Format

The combined log format is very similar to the common log format but contains few extra pieces of information.

Its defined in the /etc/apache2/apache2.conf configuration file and its format look like this:

Output:
127.0.0.1 alice Alice [06/May/2021:11:18:36 +0200] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"

Enter fullscreen mode

Exit fullscreen mode

These are the extra pieces of information (aside from those present in the common format):

Читайте также:  Установка даты и времени через терминал



Custom Log Format

LogFormat "%{User-agent}i" custom

Enter fullscreen mode

Exit fullscreen mode

In the virtual host file, we will use the CustomLog directive to set the format of the log messages to the custom and log file to the default access log.

CustomLog ${APACHE_LOG_DIR}/access.log custom

Enter fullscreen mode

Exit fullscreen mode

Now, we make a request and the Apache server will log the information about the browser that made the request into the access.log file. The log message will look like this:

Output:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36

Enter fullscreen mode

Exit fullscreen mode

Logging Into Multiple Files
You can also write multiple messages into multiple files. This can be done by using the CustomLog directive more than once. Note that when logging into the custom log file, the log file has to be manually created before you can log into it.

CustomLog ${APACHE_LOG_DIR}/custom.log custom
CustomLog ${APACHE_LOG_DIR}/access.log common

Enter fullscreen mode

Exit fullscreen mode

What Are Apache Logs?

Apache logs are text files that contain all the information on what the Apache server is doing. They provide insight into which resources were accessed, when they were accessed, who accessed them, and metrics related to that. They also include information about the errors that happened, resource mapping process, the final resolution of the connection, and many, many more.

In general, the whole Apache logging process comes in multiple phases. First, you need to store the logs somewhere for historical analytical purposes. Second, you need to analyze the logs and parse them to retrieve useful information and metrics. And finally, you may want to graph the data as the visual representation is easier to analyze and understand for a human person.

What Is the Apache Access Log?

The Apache access logs are text files that include information about all the requests processed by the Apache server. You can expect to find information like the time of the request, the requested resource, the response code, time it took to respond, and the IP address used to request the data.

Apache Access Logs Location

The location of the Apache server access log differs depending on the operating system that you are using.

  • On Red Hat, CentOS, or Fedora Linux, the access logs can be found in the /var/log/httpd/access_log by default.
  • On Debian and Ubuntu, you can expect to find the Apache logs in the /var/log/apache2/access.log and
  • FreeBSD will have the Apache server access logs stored in /var/log/httpd-access.log file.

You can configure its location using the CustomLog directive, for example:

CustomLog "/var/log/httpd-access.log"

Apache Access Log Format Configuration

Before we learn about the different log formats, let’s discuss what the Apache HTTP can do when it comes to formatting. There are two most common access log types that you can use and that the Apache server will translate to meaningful information:

  • Common Log Format
  • Combined Log Format

The log formatting directives are used in combination with the LogFormat option:

LogFormat "%t %h %m \"%r\"" custom

The above line tells that the “%t %h %m \”%r\”” format should be used and assigned to an alias called custom. After that, we can use the custom alias when defining Apache logging. For example:

CustomLog "logs/my_custom_log" custom

The above section will tell Apache to write logs in the logs/my_custom_log file with the format defined by the custom alias. The above configuration will result in logging:

  • time of the request thanks to the %t directive,
  • remote hostname thanks to the %h directive,
  • HTTP method thanks to the %m directive,
  • the first line of the request surrounded by double quotes thanks to the %r directive.

Of course, there are way more directives that can be used and the complete list can be found in the mod_log_config documentation of the Apache server.

Common Log Format

LogFormat "%h %l %u %t \"%r\" %>s %b" common

Here’s how an access log from that log file looks like:

10.1.2.3 - rehg [10/Nov/2021:19:22:12 -0000] "GET /sematext.png HTTP/1.1" 200 3423
  • %h, resolved into 10.1.2.3 – the IP address of the remote host that made the request.
  • %l, remote log name provided by identd, in our case a hyphen is provided, which is a value that we can expect to be logged in a case when the information provided by the logging directive is not found or can’t be accessed.
  • %u, resolved into rehg, the user identifier determined by the HTTP authentication.
  • %t, the date and time of the request with the time zone, in the above case it is [10/Nov/2021:19:22:12 -0000]
  • \”%r\”, the first line of the request inside double quotes, in the above case it is: “GET /sematext.png HTTP/1.1”
  • %>s, the status code reported to the client. This information is crucial because it determines whether the request was successful or not.
  • %b, the size of the object sent to the client, in our case the object was the sematext.png file and its size was 3423 bytes.

Combined Log Format

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

And the example log line produced by the above log line looks like this:

10.1.2.3 - grah [12/Nov/2021:14:25:32 -0000] "GET /sematext.png HTTP/1.1" 200 3423 "http://www.sematext.com/index.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.74 Safari/537.36 Edg/79.0.309.43"

Custom Log Format

There is one more thing that we should discuss when it comes to Apache Server logging configuration – the CustomLog directive. We’ve already seen that configuration directive, but let’s discuss that in greater details.

Multiple Access Logs

To do that we need to include multiple CustomLog sections in our configuration file:

LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog logs/agent_log "%t %{User-agent}i %>s"
CustomLog logs/referer_log "%t %h %{Referer}i"
CustomLog logs/access_log common

You can see that this time we didn’t use three separate LogFormat configuration options, but we’ve specified the apache log format in the CustomLog format line. This is also possible and very convenient when the formatting of the log lines is used only in that given file.

Conditional Logs

SetEnvIf Request_URI \.png$ png-image-log
CustomLog "png-access.log" common env=png-image-log

Logs Rotation and Piped Logs

Depending on the logging configuration and the traffic that your Apache servers are handling, logging can be extensive. All the logs that you keep on the machine take space and if you are not using a log centralization solution like Sematext Logs, you will have to deal with space and management of logs.

Let’s talk about log rotation first. Log rotation is a process of creating a new log file that the Apache HTTP server will start writing to and renaming the old log file, so it is no longer updated. The log rotation happens when you gracefully restart the server. That means that without any kind of client requests processing interruption a new log file is created. In production environments, you would like to restart the Apache servers though.

That’s why the Apache server supports piped logs. Instead of writing the log events to a file, you use the piped logs to send the log events to a different application that will handle the log processing – for example to rotatelogs:

CustomLog "|/usr/local/apache/bin/rotatelogs /var/log/access.log 86400" common

The rotatelogs application comes with Apache server and is capable of rotating logs without the need of restarting the server. The above example will result in rotating the /var/log/access.log file every 24 hours.

How to Read Apache Access Logs

Apache server access logs are just simple text files. They can be easily opened by any tool that can read such files. On Linux-based systems, this can be the cat command-line tool or tail if you want to monitor the log lines as they go.

There are two caveats, though. The first is access policies. You may not have access to the machines running Apache HTTP server and even if you do, you may not have read access to the appropriate log directories. The second is distribution. It is not uncommon to have multiple Apache servers distributed across multiple data centers. In such a case, it is way easier to use a dedicated observability tool such as Sematext Logs that will provide not only the option to look into the raw files but also aggregated information into the key metrics derived for them.

Understanding Apache Access Logs

Our Apache access logs files are easy to read and not hard to understand either. Just remember about the patterns that you’ve used in your configuration. We’ve already covered the common patterns that you can encounter in the Apache log files. Keep in mind that understanding the log files is even easier with log analysis tools that do the parsing for you and give you an aggregated view of the data which is easier to understand.

Step 5 — Configuring Apache Error Logs

The error log contains information about the errors the web server encountered while processing the request. A common error while processing the request is a request for a missing file.

You can choose to which file the error messages will be stored using the ErrorLog directive in your virtual host configuration file. This directive takes one argument — path to the log file. Here is an example from default virtual host configuration file /etc/apache2/sites-available/000-default.conf

ErrorLog ${APACHE_LOG_DIR}/error.log

Enter fullscreen mode

Exit fullscreen mode

You can choose a custom file but be aware as the file has to be manually created before you can log into it.

In the virtual host configuration file, you can also specify the level of errors that will be logged using the LogLevel directive. Setting this option to a specific value, the server will ignore errors with lover severity then set in the LogLevel directive. It is not recommended to change it to higher values than error.

These are the possible values:

trace1 — trace8 — Trace messages (LOWEST)
debug — messages used for debugging
info — informational messages
notice — notices
warn — warnings
error — errors while processing the request (doesn’t require immediate action)
crit — Critical error that requires prompt action
alert — Error that requires immediate action
emerg — System is unusable
You can set the log level using the LogLevel directive like this:

LogLevel info

Enter fullscreen mode

Exit fullscreen mode

If the log level is not set, the server will set the log level to warn by default.

Conclusion

Having Apache metrics and logs in the same place, being able to slice and dice them, being alerted when issues appear and having insight into every piece of your environment is no longer something good to have but need to have. All of that and more is provided by Sematext Cloud, an observability platform with dedicated Apache server logs and metrics support. Built with simplicity in mind and requiring no credit card, nothing stops you from giving it a try to see how it can improve your log management and log analysis processes.

Start Free Trial


Conclusion

In this tutorial, you learned what types of log Apache web server stores, where you can find those logs, how to understand the formatting, and how to create your custom log formats. Now, you can log into multiple files and set the level of errors to which the server will react. At this point, you know everything you need to efficiently debug your web application.

You can explore more on linux logging in logtail tutorial library.

Оцените статью
Хостинги