Журнал ошибок сервера apache

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

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

В этой статье мы рассмотрим модули журналирования, которые являются стандартной частью http сервера.

Логи Apache в Windows

В Windows имеются особенности настройки имени файла журнала — точнее говоря, пути до файла журнала. Если имена файлов указываются с начальной буквы диска, например «C:/«, то сервер будет использовать явно указанный путь. Если имена файлов НЕ начинаются с буквы диска, то к указанному значению добавляется значение ServerRoot — то есть «logs/access.log» с ServerRoot установленной на «c:/Server/bin/Apache24″, будет интерпретироваться как «c:/Server/bin/Apache24/logs/access.log«, в то время как «c:/logs/access.log» будет интерпретироваться как «c:/logs/access.log«.

Также особенностью указания пути до логов в Windows является то, что нужно использовать слэши, а не обратные слэши, то есть «c:/apache» вместо «c:\apache«. Если пропущена буква диска, то по умолчанию будет использоваться диск, на котором размещён httpd.exe. Рекомендуется явно указывать букву диска при абсолютных путях, чтобы избежать недоразумений.

Apache error: ошибки сервера и сайтов

Путь до файла журнала с ошибками указывается с помощью ErrorLog, например, для сохранения ошибок в папке «logs/error.log» относительно корневой папки веб-сервера:

ErrorLog "logs/error.log"

Если не указать директиву ErrorLog внутри контейнера <VirtualHost>, сообщения об ошибках, относящиеся к этому виртуальному хосту, будут записаны в этот общий файл. Если в контейнере <VirtualHost> вы указали путь до файла журнала с ошибками, то сообщения об ошибках этого хоста будут записываться там, а не в этот файл.

С помощью директивы LogLevel можно установить уровень важности сообщений, которые должны попадать в журнал ошибок. Доступные варианты:

  • debug
  • info
  • notice
  • warn
  • error
  • crit
  • alert
  • emerg

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

Журнал ошибок обычно записывается в файл (обычно это error_log в системах Unix и error.log в Windows и OS/2). В системах Unix также возможно, чтобы сервер отправлял ошибки в системный журнал или передавал их программе.

Формат журнала ошибок определяется директивой ErrorLogFormat, с помощью которой вы можете настроить, какие значения записываются в журнал. По умолчанию задан формат, если вы его не указали. Типичное сообщение журнала следующее:

[Fri Sep 09 10:42:29.902022 2011] [core:error] [pid 35708:tid 4328636416] [client 72.15.99.187] File does not exist: /usr/local/apache2/htdocs/favicon.ico

Первый элемент в записи журнала — это дата и время сообщения. Следующим является модуль, создающий сообщение (в данном случае ядро) и уровень серьёзности этого сообщения. За этим следует идентификатор процесса и, если необходимо, идентификатор потока процесса, в котором возникло условие. Далее у нас есть адрес клиента, который сделал запрос. И, наконец, подробное сообщение об ошибке, которое в этом случае указывает на запрос о несуществующем файле.

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

Если поместить токен %L в журнал ошибок и журнал доступа, будет создан идентификатор записи журнала, с которым вы можете сопоставить запись в журнале ошибок с записью в журнале доступа. Если загружен mod_unique_id, его уникальный идентификатор запроса также будет использоваться в качестве идентификатора записи журнала.

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

tail -f error_log

Apache access: логи доступа к серверу

Журнал доступа к серверу записывает все запросы, обработанные сервером. Расположение и содержимое журнала доступа контролируются директивой CustomLog. Директива LogFormat может быть использована для упрощения выбора содержимого журналов. В этом разделе описывается, как настроить сервер для записи информации в журнал доступа.

Различные версии Apache httpd использовали разные модули и директивы для управления журналом доступа, включая mod_log_referer, mod_log_agent и директиву TransferLog. Директива CustomLog теперь включает в себя функциональность всех старых директив.

Формат журнала доступа легко настраивается. Формат указывается с использованием строки формата, которая очень похожа на строку формата printf в стиле C. Некоторые примеры представлены в следующих разделах. Полный список возможного содержимого строки формата смотрите здесь: https://httpd.apache.org/docs/current/mod/mod_log_config.html

Общий формат журнала (Common Log)

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

LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog logs/access_log common

В первой строке задано имя (псевдоним) common, которому присвоено в качестве значения строка «%h %l %u %t \»%r\» %>s %b«.

Строка формата состоит из директив, начинающихся с символа процента, каждая из которых указывает серверу регистрировать определённый фрагмент информации. Литеральные (буквальные) символы также могут быть помещены в строку формата и будут скопированы непосредственно в вывод журнала. Символ кавычки («) должен быть экранирован путём размещения обратной косой черты перед ним, чтобы он не интерпретировался как конец строки формата. Строка формата также может содержать специальные управляющие символы «\n«для новой строки и «\t» для обозначения таба (табуляции).

В данной строке значение директив следующее:

  • %h — имя удалённого хоста. Будет записан IP адрес, если HostnameLookups установлен на Off, что является значением по умолчанию.
  • %l — длинное имя удалённого хоста (от identd, если предоставит). Это вернёт прочерк если не присутствует mod_ident и IdentityCheck не установлен на On.
  • %u — удалённый пользователь, если запрос был сделан аутентифицированным пользователем. Может быть фальшивым, если возвращён статус (%s401 (unauthorized).
  • %t — время получения запроса в формате [18/Sep/2011:19:18:28 -0400]. Последнее показывает сдвиг временной зоны от GMT
  • \»%r\» — первая строка запроса, помещённая в буквальные кавычки
  • %>s — финальный статус. Если бы было обозначение %s, то означало бы просто статус — для запросов, которые были внутренне перенаправлены это обозначало бы исходный статус.
  • %b — размер ответа в байтах, исключая HTTP заголовки. В формате CLF, то есть ‘‘ вместо 0, когда байты не отправлены.

Директива CustomLog устанавливает новый файл журнала, используя определённый псевдоним. Имя файла для журнала доступа относительно ServerRoot, если оно не начинается с косой черты (буквы диска).

Приведённая выше конфигурация будет сохранять записи журнала в формате, известном как Common Log Format (CLF). Этот стандартный формат может создаваться многими различными веб-серверами и считываться многими программами анализа журналов. Записи файла журнала, созданные в CLF, будут выглядеть примерно так:

127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326

Каждая часть этой записи журнала описана ниже.

127.0.0.1 (%h)

Это IP-адрес клиента (удалённого хоста), который сделал запрос к серверу. Если для HostnameLookups установлено значение On, сервер попытается определить имя хоста и зарегистрировать его вместо IP-адреса. Однако такая конфигурация не рекомендуется, поскольку она может значительно замедлить работу сервера. Вместо этого лучше всего использовать постпроцессор журнала, такой как logresolve, для определения имён хостов. Указанный здесь IP-адрес не обязательно является адресом машины, на которой сидит пользователь. Если между пользователем и сервером существует прокси-сервер, этот адрес будет адресом прокси, а не исходной машины.

— (%l)

«Дефис» в выходных данных указывает на то, что запрошенная часть информации недоступна. В этом случае информация, которая недоступна, является идентификационной информацией клиента RFC 1413, определённой с помощью id на клиентском компьютере. Эта информация крайне ненадёжна и почти никогда не должна использоваться, кроме как в жёстко контролируемых внутренних сетях. Apache httpd даже не будет пытаться определить эту информацию, если для IdentityCheck не установлено значение On.

frank (%u)

Это идентификатор пользователя, запрашивающего документ, как определено HTTP-аутентификацией. Такое же значение обычно предоставляется сценариям CGI в переменной среды REMOTE_USER. Если код состояния для запроса равен 401, то этому значению не следует доверять, поскольку пользователь ещё не аутентифицирован. Если документ не защищён паролем, эта часть будет ««, как и предыдущая.

[10/Oct/2000:13:55:36 -0700] (%t)

Время получения запроса. Формат такой:

[день/месяц/год:час:минута:секунда зона]

день = 2*цифры

месяц = 3*цифры

год = 4*цифры

час = 2*цифры

минута = 2*цифры

секунда = 2*цифры

зона = (`+’ | `-‘) 4*цифры

Можно отобразить время в другом формате, указав %{format}t в строке формата журнала, где формат такой же, как в strftime(3) из стандартной библиотеки C, или один из поддерживаемых специальных токенов. Подробности смотрите в строках формате строки mod_log_config.

«GET /apache_pb.gif HTTP/1.0» (\»%r\»)

Строка запроса от клиента указана в двойных кавычках. Строка запроса содержит много полезной информации. Во-первых, клиент использует метод GET. Во-вторых, клиент запросил ресурс /apache_pb.gif, и в-третьих, клиент использовал протокол HTTP/1.0. Также возможно зарегистрировать одну или несколько частей строки запроса независимо. Например, строка формата «%m %U%q %H» будет регистрировать метод, путь, строку запроса и протокол, что приведёт к тому же результату, что и «%r«.

200 (%>s)

Это код состояния, который сервер отправляет обратно клиенту. Эта информация очень ценна, потому что она показывает, привёл ли запрос к успешному ответу (коды начинаются с 2), к перенаправлению (коды начинаются с 3), к ошибке, вызванной клиентом (коды начинаются с 4), или к ошибкам в сервер (коды начинаются с 5). Полный список возможных кодов состояния можно найти в спецификации HTTP (RFC2616 раздел 10).

2326 (%b)

Последняя часть указывает размер объекта, возвращаемого клиенту, не включая заголовки ответа. Если контент не был возвращён клиенту, это значение будет ««. Чтобы записать «0» без содержимого, вместо %b используйте %B.

Логи комбинированного формата (Combined Log)

Другая часто используемая строка формата называется Combined Log Format. Может использоваться следующим образом.

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

Этот формат точно такой же, как Common Log Format, с добавлением ещё двух полей. Каждое из дополнительных полей использует директиву начинающуюся с символа процента %{заголовок}i, где заголовок может быть любым заголовком HTTP-запроса. Журнал доступа в этом формате будет выглядеть так:

127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 "http://www.example.com/start.html" "Mozilla/4.08 [en] (Win98; I ;Nav)"

Дополнительными полями являются:

«http://www.example.com/start.html» (\»%{Referer}i\»)

Referer — это часть заголовок HTTP-запроса, которая называется также Referer. В этой строке содержится информация о странице, с которой клиент был прислан на данный сайт. (Это должна быть страница, которая ссылается или включает /apache_pb.gif).

«Mozilla/4.08 [en] (Win98; I ;Nav)» (\»%{User-agent}i\»)

Заголовок HTTP-запроса User-Agent. Это идентифицирующая информация, которую клиентский браузер сообщает о себе.

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

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access.log" common   
</IfModule> 

Как можно увидеть, установлены три псевдонима: combined, common и combinedio. При этом по умолчанию используется common. При желании вы без труда сможете переключиться на combined или настроить формат строки лога под свой вкус.

Например, если вы предпочитаете, чтобы в файле лога доступа также присутствовала информация о пользовательском агенте и реферере, то есть Combined Logfile Format, то вы можете использовать следующую директиву:

CustomLog "logs/access.log" combined

Связанные статьи:

  • Почему в логах ошибок Apache не сохраняются записи об ошибке 404 (100%)
  • Как в Apache под Windows настроить автоматическую ротацию и очистку логов (100%)
  • Удалённый просмотр и поиск по логам Apache в Windows (модуль mod_view) (100%)
  • Apache для Windows (54.5%)
  • Как запустить Apache на Windows (54.5%)
  • Что делать если PHP скрипту не хватает времени и памяти. Почему большой файл не загружается на сайт или в phpMyAdmin (RANDOM — 50%)

At the time of writing, the Apache HTTP server is
used by 30.8% of all web
servers in operation. If you’re responsible for managing any system that
utilizes Apache, then you will surely interact with its logging infrastructure
on a regular basis. This tutorial will introduce you to logging in Apache and
how it can help you diagnose, troubleshoot, and quickly resolve any problem you
may encounter on your server.

You will learn where logs are stored, how to access them, and how to customize
the log output and location to fit your needs. You will also learn how to
centralize Apache logs in a log management system for easier tracing, searching,
and filtering of logs across your entire stack.

🔭 Want to centralize and monitor your Apache logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

Prerequisites

To follow through with this tutorial, you should set up a Linux server that
includes a non-root user with sudo privileges. Additionally, you also need the
Apache HTTP server installed and enabled on the server, which can be done by
executing the relevant commands below.

On Debian-based distributions like Ubuntu:

sudo systemctl enable apache2
sudo systemctl start apache2

On RHEL, Fedora or CentOS:

sudo systemctl enable httpd
sudo systemctl start httpd

Please note that the rest of the commands, directory configurations, and
conventions used in this tutorial pertain to Debian-based distributions like
Ubuntu. Still, the concepts remain the same for other distributions.

Step 1 — Getting started with Apache logging

Apache logs are files that record everything the Apache web server is doing for
later analysis by the server administrator. The records of all Apache events are
placed in two different text files:

  • Access Log: this file stores information about incoming requests. You’ll
    find details about each request such as the requested resource, response
    codes, time taken to generate the response, IP address of the client, and
    more.
  • Error Log: this file contains diagnostic information about any errors were
    encountered while processing requests.

Step 2 — Locating the Apache log files

The log files’ location depends on the operating system the Apache web server is
running. On Debian-based operating systems like Ubuntu, the access log file is
located in /var/log/apache2/access.log. On CentOS, RHEL, or Fedora, the access
log file is stored in /var/log/httpd/access_log.

A typical access log entry might look like this:

::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"

Similarly, the error log file is located in /var/log/apache2/error.log on
Debian-based systems and /var/log/httpd/error_log on CentOS, RHEL, or Fedora.
A typical error log entry might look like this:

[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

In the next section, we’ll discuss how to view these log files from the command
line.

Step 3 — Viewing Apache Log files

One of the most common ways to view an Apache log file is through the tail
command which prints the last 10 lines from a file. When the -f option is
supplied, the command will watch the file and output its contents in real-time.

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

You should observe the following output on the screen:

. . .

198.54.132.137 - - [04/Feb/2022:11:34:04 +0000] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:04 +0000] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:04 +0000] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:05 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:06 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:06 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:07 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:07 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"

To view the entire contents of the file, you can use the cat command or open
the file in a text editor like nano or vim:

cat /var/log/apache2/access.log

You may also want to filter the log entries in the log file by a specific term.
In such cases, you should use the grep command. The first argument to grep
is the term you want to search for, while the second is the log file that will
be searched. In example below, we are filtering all the lines that contain the
word GET:

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

This should present the following output:

. . .

198.54.132.137 - - [04/Feb/2022:11:34:04 +0000] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:04 +0000] "GET / HTTP/1.1" 200 3477 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:05 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:06 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:06 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:07 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
198.54.132.137 - - [04/Feb/2022:11:34:07 +0000] "GET / HTTP/1.1" 200 3476 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"

Step 4 — Examining Apache access log formats

The access log records all requests that are processed by the server. You can
see what resources are being requested, the status of each request, and how long
it took to process their response. In this section, we’ll dive deeper into how
to customize the information that is displayed in this file.

Before you can derive value from reading a log file, you need to understand the
format that is being used for each of its entries. The CustomLog directive is
what controls the location and format of the Apache access log file. This
directive can be placed in the server configuration file
(/etc/apache2/apache2.conf) or in your virtual host entry. Note that defining
the same CustomLog directive in both files may cause problems.

Let’s look at the common formats used in Apache access logs and what they mean.

Common Log Format

The Common Log Format
is the standardized access log format format used by many web servers because it
is easy to read and understand. It is defined in the /etc/apache2/apache2.conf
configuration file through the LogFormat directive.

When you run the command below:

sudo grep common /etc/apache2/apache2.conf

You will observe the following output:

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

The line above defines the nickname common and associates it with a particular
log format string. A log entry produced by this format will look like this:

127.0.0.1 alice Alice [06/May/2021:11:26:42 +0200] "GET / HTTP/1.1" 200 3477

Here’s an explanation of the information contained in the log message above:

  • %h -> 127.0.0.1: the hostname or IP address of the client that made the
    request.
  • %l -> alice: remote log name (name used to log in a user). A placeholder
    value (-) will be used if it is not set.
  • %u -> Alice: remote username (username of logged-in user). A placeholder
    value (-) will be used if it is not set.
  • %t -> [06/May/2021:11:26:42 +0200]: the day and time of the request.
  • \"%r\" -> "GET / HTTP/1.1" — the request method, route, and protocol.
  • %>s -> 200 — the response code.
  • %O -> 3477 — the size of the response in bytes.

Combined Log Format

The Combined Log Format
is very similar to the Common log format but contains few extra pieces of
information.

It’s also defined in the /etc/apache2/apache2.conf configuration file:

sudo grep -w combined /etc/apache2/apache2.conf

You will observe the following output:

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

Notice that it is exactly the same as the Common Log Format, with the addition
of two extra fields. Entries produced in this format will look like this:

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"

Here’s an explanation of the two additional fields that are not present in the
Common log format:

  • \"%{Referer}i\" -> "-": the URL of the referrer (if available, otherwise
    - is used).
  • \"%{User-Agent}i\" ->
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36":
    detailed information about the user agent of the client that made the request.

Step 5 — Creating a custom log format

You can define a custom log format in the /etc/apache2/apache2.conf file by
using the LogFormat directive followed by the actual format of the output and
a nickname that will be used as an identifier for the format. After defining the
custom format, you’ll pass its nickname to the CustomLog directive and restart
the apache2 service.

In this example, we will create a log format named custom that looks like
this:

LogFormat "%t %H %m %U %q %I %>s %O %{ms}T" custom

Open your /etc/apache2/apache2.conf file and place the line above below the
other LogFormat lines. It will produce access log entries with the following
details:

  • %t: date and time of the request.
  • %H: the request protocol.
  • %m: the request method.
  • %U: the URL path requested.
  • %q: query parameters (if any).
  • %I: total bytes received including the request headers.
  • %>s: final HTTP status code.
  • %O: number of bytes sent in the response.
  • %{ms}T: time taken to generate the response in milliseconds.

You can find all other formatting options and their description on
this page.

To enable the custom format for subsequent access log entries, you must change
the value of the CustomLog directive in your virtual hosts file and restart
the apache2 service with Systemctl.

Open up the default virtual hosts file using the command below:

sudo nano /etc/apache2/sites-available/000-default.conf

Find the following line:

CustomLog ${APACHE_LOG_DIR}/access.log combined

And change it to:

CustomLog ${APACHE_LOG_DIR}/access.log combined

Save the file by pressing Ctrl-O then Ctrl-X, then restart the apache2
service using the command below:

sudo systemctl restart apache2

Afterward, make the following request to your server using curl:

curl --head 'http://<your_server_ip>?name=john&age=30'

You should observe the following response:

HTTP/1.1 200 OK
Date: Mon, 07 Feb 2022 14:21:45 GMT
Server: Apache/2.4.41 (Ubuntu)
Last-Modified: Mon, 07 Feb 2022 12:57:29 GMT
ETag: "2aa6-5d76d24a738bc"
Accept-Ranges: bytes
Content-Length: 10918
Vary: Accept-Encoding
Content-Type: text/html

Go ahead and view the last 10 messages in the access log file:

sudo tail /var/log/apache2/access.log

The log entry that describes the request will look like this:

[07/Feb/2022:14:21:45 +0000] HTTP/1.1 HEAD /index.html ?name=john&age=30 96 200 255 0

It’s also possible to create multiple access log files by specifying the
CustomLog directive more than once. In the example below, the first line logs
into a custom.log file using the custom log format, while the second uses
the common format to write entries into access.log. Similarly, the
combined.log file contains messages formatted according to the combined log
format.

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

Step 6 — Formatting your logs as JSON

Although many log management systems support the default Apache logging formats,
it might be best to log in a structured format like JSON since that’s the go-to
format for structured logging in the industry and it is universally supported.
Here’s a conversion of our custom log format into JSON:

LogFormat "{ \"timestamp\":\"%t\", \"protocol\":\"%H\", \"method\":\"%m\", \"request\":\"%U\", \"query\":\"%q\", \"request_size_in_bytes\":\"%I\", \"status_code\":\"%>s\", \"response_size_in_bytes\":\"%O\", \"time_taken_ms\":\"%{ms}T\" }" json

This produces log entries with the following formatting:

{
  "timestamp": "[07/Feb/2022:15:09:02 +0000]",
  "protocol": "HTTP/1.1",
  "method": "HEAD",
  "request": "/index.html",
  "query": "?name=john&age=30",
  "request_size_in_bytes": "96",
  "status_code": "200",
  "response_size_in_bytes": "255",
  "time_taken_ms": "0"
}

Step 7 — Configuring Apache error logs

The server error log contains information about any errors that the web server
encountered while processing incoming requests as well as other diagnostic
information. You can choose where the error messages will be transported to
using the ErrorLog directive in your virtual host configuration file. This
transport is usually a log file on the filesystem.

Here is an example from default virtual host configuration file
/etc/apache2/sites-available/000-default.conf:

ErrorLog ${APACHE_LOG_DIR}/error.log

On Debian-based distributions, the default error log is in the
/var/log/apache2/error.log file, while in Fedora/CentOS/RHEL, it placed in the
/var/log/httpd/error_log file. If the path argument to ErrorLog is not
absolute, then it is assumed to be relative to the
ServerRoot.

A common practice is to monitor the error log continuously for any problems
during development or testing. This is easily achieved through the tail
command:

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

You will observe the following output:

[Mon Feb 07 13:03:43.445444 2022] [core:notice] [pid 10469:tid 140561300880448] AH00094: Command line: '/usr/sbin/apache2'
[Mon Feb 07 13:07:31.528850 2022] [mpm_event:notice] [pid 10469:tid 140561300880448] AH00491: caught SIGTERM, shutting down
[Mon Feb 07 13:07:31.626878 2022] [mpm_event:notice] [pid 10864:tid 140224997284928] AH00489: Apache/2.4.41 (Ubuntu) configured -- resuming normal operations
[Mon Feb 07 13:07:31.626980 2022] [core:notice] [pid 10864:tid 140224997284928] AH00094: Command line: '/usr/sbin/apache2'
[Mon Feb 07 13:13:25.966501 2022] [mpm_event:notice] [pid 10864:tid 140224997284928] AH00491: caught SIGTERM, shutting down
[Mon Feb 07 13:13:26.049222 2022] [mpm_event:notice] [pid 11268:tid 139760377875520] AH00489: Apache/2.4.41 (Ubuntu) configured -- resuming normal operations
[Mon Feb 07 13:13:26.049318 2022] [core:notice] [pid 11268:tid 139760377875520] AH00094: Command line: '/usr/sbin/apache2'
[Mon Feb 07 15:08:50.856388 2022] [mpm_event:notice] [pid 11268:tid 139760377875520] AH00491: caught SIGTERM, shutting down
[Mon Feb 07 15:08:50.940561 2022] [mpm_event:notice] [pid 12096:tid 140473452194880] AH00489: Apache/2.4.41 (Ubuntu) configured -- resuming normal operations
[Mon Feb 07 15:08:50.940669 2022] [core:notice] [pid 12096:tid 140473452194880] AH00094: Command line: '/usr/sbin/apache2'

Aside from logging directly to a file, you can also forward your logs to a
Syslog. You can do this by
specifying syslog
instead of a file path as the argument to ErrorLog:

Step 8 — Customizing the error log format

Like the Apache access logs, the format of the error messages can be controlled
through the ErrorLogFormat directive, which should be placed in the main
config file or virtual host entry. It looks like this:

ErrorLogFormat "[%{u}t] [%l] [pid %P:tid %T] [client\ %a] %M"

The above configuration produces a log entry in the following format:

[Mon Feb 07 15:52:57.234792 2022] [error] [pid 24372:tid 24507] [client 20.113.27.135:34579] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html) found, and server-generated directory index forbidden by Options directive

Here’s an explanation of the formatting options used above:

%{u}t: the current time, including microseconds. %l: the log level of the
message. %P: the process identifier. %T: the thread identifier. %a: the
client IP address. %M: the actual log message.

Note that when the data for a formatting option is not available in a particular
event, it will be omitted from the log entirely as the Apache error log doesn’t
use placeholder values for missing parameters.

You can find a complete description of all the available error formatting
options in the
Apache docs.

Step 9 — Customizing the error log level

In the virtual host configuration file, you can also control the level of
messages that will be entered into the error log through the
LogLevel directive.
When you specify a particular value, messages from all other levels of higher
severity will be logged as well. For example, when LogLevel error is
specified, messages with a severity of crit, alert, and emerg will also be
logged.

These are the levels available in increasing order of severity:

  • trace1trace8: trace messages (lowest severity).
  • debug: messages used for debugging.
  • info: informational messages.
  • notice: normal but significant conditions.
  • warn: warnings.
  • error: error conditions that doesn’t necessarily require immediate action.
  • crit: critical conditions that requires prompt action.
  • alert: errors that require immediate action.
  • emerg: system is unusable.

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

Step 10 — Centralizing your Apache logs

Storing your Apache logs on the filesystem may suffice for development
environments or single-server deployments, but when multiple servers are
involved, it may be more convenient to centralize all your logs in a single
location so that you can automatically parse, filter, and search log data from
all sources in real-time.

In this section, we’ll demonstrate how you can centralize your Apache logs in a
log management service through Vector,
a high-performance tool for building observability pipelines. The following
instructions assume that you’ve signed up for a free
Logtail account and retrieved your source
token.

Go ahead and follow the relevant
installation instructions for Vector
for your operating system. On Ubuntu, you may run the following commands to
install the Vector CLI:

curl -1sLf \ 'https://repositories.timber.io/public/vector/cfg/setup/bash.deb.sh' \ | sudo -E bash

After Vector is installed, confirm that it is up and running through
systemctl:

You should observe that it is active and running:

● vector.service - Vector
     Loaded: loaded (/lib/systemd/system/vector.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2022-02-08 10:52:59 UTC; 48s ago
       Docs: https://vector.dev
    Process: 18586 ExecStartPre=/usr/bin/vector validate (code=exited, status=0/SUCCESS)
   Main PID: 18599 (vector)
      Tasks: 3 (limit: 2275)
     Memory: 6.8M
     CGroup: /system.slice/vector.service
             └─18599 /usr/bin/vector

Otherwise, go ahead and start it with the command below.

sudo systemctl start vector

Afterwards, change into a root shell and append your Logtail vector
configuration for Apache into the /etc/vector/vector.toml file using the
command below. Don’t forget to replace the <your_logtail_source_token>
placeholder below with your source token.

wget -O ->> /etc/vector/vector.toml \
    https://logtail.com/vector-toml/apache2/<your_logtail_source_token>

Then restart the vector service:

sudo systemctl restart vector

You will observe that your Apache logs will start coming through in Logtail:

Conclusion

In this tutorial, you learned about the different types of logs that the Apache
web server stores, where you can find those logs, and how to view their
contents. We also discussed Apache access and error log formatting and how to
create your custom log formats, including a structured JSON format. Finally, we
considered how you can manage all your Apache logs in one place by using the
Vector CLI to stream each entry to a log management service.

Don’t forget to read the docs to
find out more about all the logging features that Apache has to offer. Thanks
for reading!

Author's avatar

Article by

Ayooluwa Isaiah

Ayo is the Head of Content at Better Stack. His passion is simplifying and communicating complex technical ideas effectively. His work was featured on several esteemed publications including LWN.net, Digital Ocean, and CSS-Tricks. When he’s not writing or coding, he loves to travel, bike, and play tennis.

Centralize all your logs into one place.

Analyze, correlate and filter logs with SQL.

Create actionable

dashboards.

Share and comment with built-in collaboration.

Got an article suggestion?
Let us know

Next article

How to View and Configure NGINX Access & Error Logs

Learn how to view and configure nginx access and error logs

Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

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

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

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

В этой статье описывается, как настроить и прочитать журналы доступа и ошибок Apache.

Настройка журнала доступа

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

Директива CustomLog определяет расположение файла журнала и формат регистрируемых сообщений.

Базовый синтаксис директивы CustomLog следующий:

CustomLog log_file format [condition];

log_file может относиться либо к ServerRoot либо к полному пути к файлу журнала. Сообщения журнала также можно передать другой программе с помощью символа вертикальной черты | .

Второй аргумент, format определяет формат сообщений журнала. Это может быть явное определение формата или псевдоним, определяемый директивой LogFormat .

LogFormat "%h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" combined
CustomLog logs/access.log combined
CustomLog logs/access.log "%h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i""

Чтобы не повторять один и тот же код несколько раз, предпочтительнее определить директиву LogFormat и использовать ее в качестве псевдонима в директиве CustomLog .

Полный список всех строк формата и модификаторов см. В документации модуля «mod_log_config» .

Третий аргумент [condition] является необязательным и позволяет записывать сообщения журнала только при выполнении определенного условия. Обычно это делается с использованием переменных окружения. Условие может быть отменено с помощью ! условное обозначение.

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

SetEnvIf Request_URI .css$ css-file
CustomLog logs/access.log custom env=!css-file

Чтобы изменить формат ведения журнала, вы можете определить новую директиву LogFormat или переопределить формат по умолчанию. Обычно лучше определить новый формат.

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

Для этого просто закомментируйте или удалите директиву CustomLog из разделов конфигурации основного сервера и виртуального сервера.

Если вы хотите отключить журнал доступа только для одного виртуального хоста, установите для первого аргумента директивы CustomLog значение /dev/null :

CustomLog /dev/null combined

Настройка журнала ошибок

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

Директива ErrorLog определяет расположение имени журнала ошибок. Он имеет следующий вид:

Если путь к log_file не является абсолютным, он устанавливается относительно ServerRoot . Сообщения об ошибках также могут быть переданы другой программе с помощью символа вертикальной черты | .

Параметр LogLevel устанавливает уровень ведения журнала. Ниже перечислены уровни в порядке их серьезности (от низкого до высокого):

  • trace1trace8 — сообщения трассировки.
  • debugdebug сообщения.
  • info — Информационные сообщения.
  • notice — Уведомления.
  • warn — Предупреждения.
  • error — Ошибки при обработке запроса.
  • crit — Критические проблемы. Требуется быстрое действие.
  • alert — Оповещения. Действия должны быть предприняты немедленно.
  • emerg — Чрезвычайная ситуация. Система находится в непригодном для использования состоянии.

Каждый уровень журнала включает в себя более высокие уровни. Например, если вы установите уровень журнала , чтобы warn , Apache также записывает error , crit , alert и emerg сообщения.

Если параметр LogLevel не указан, по умолчанию используется warn . Рекомендуется установить уровень как минимум crit .

Директива ErrorLogFormat определяет формат журнала ошибок. В большинстве дистрибутивов Linux сервер Apache использует формат по умолчанию, которого достаточно в большинстве случаев.

Виртуальные хосты и глобальное ведение журнала

Поведение журнала и расположение файлов можно установить глобально или для каждого виртуального хоста.

Затем в контексте основного сервера ErrorLog директивы CustomLog или ErrorLog , сервер записывает все сообщения журнала в те же файлы журнала доступа и ошибок. В противном случае, если директивы помещаются в блок <VirtualHost> , в указанный файл записываются только сообщения журнала для этого виртуального хоста.

Директива журнала, установленная в блоке <VirtualHost> заменяет директиву, установленную в контексте сервера.

Виртуальные хосты без директив CustomLog или ErrorLog будут записывать свои сообщения журнала в глобальные журналы сервера.

Для лучшей читаемости рекомендуется установить отдельные файлы журнала доступа и ошибок для каждого виртуального хоста. Вот пример:

<VirtualHost *:80>
     ServerName example.com
     ServerAlias www.example.com
     ServerAdmin [email protected]
     DocumentRoot /var/www/example.com/public
     LogLevel warn
     ErrorLog /var/www/example.com/logs/error.log
     CustomLog /var/www/example.com/logs/access.log combined
</VirtualHost>

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

Расположение файлов журнала

По умолчанию в дистрибутивах на основе Debian, таких как Ubuntu , журналы доступа и ошибок расположены в каталоге /var/log/apache2 . В CentOS файлы журнала помещаются в каталог /var/log/httpd .

Чтение и понимание файлов журнала Apache

Файлы журнала можно открывать и анализировать с помощью стандартных команд, таких как cat , less , grep , cut , awk и т. Д.

Вот пример записи из файла журнала доступа, в котором используется формат журнала combine Debian:

192.168.33.1 - - [08/Jan/2020:21:39:03 +0000] "GET / HTTP/1.1" 200 6169 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"

Давайте разберемся, что означает каждое поле записи:

  • %h192.168.33.1 — Имя хоста или IP-адрес клиента, выполняющего запрос.
  • %l- — Имя удаленного журнала. Если имя пользователя не задано, в этом поле отображается - .
  • %u- — Если запрос аутентифицирован, отображается имя удаленного пользователя.
  • %t[08/Jan/2020:21:39:03 +0000] — Время локального сервера.
  • "%r""GET / HTTP/1.1" — первая строка запроса. Тип запроса, путь и протокол.
  • %>s200 — окончательный код ответа сервера. Если символ > не используется и запрос был перенаправлен внутри, он покажет статус исходного запроса.
  • %O396 — Размер ответа сервера в байтах.
  • "%{Referer}i""-" — URL перехода.
  • "%{User-Agent}i"Mozilla/5.0 ... — Пользовательский агент клиента (веб-браузера).

Используйте команду tail для просмотра файла журнала в режиме реального времени:

tail -f access.log 

Выводы

Файлы журналов содержат полезную информацию о проблемах с сервером и о том, как посетители взаимодействуют с вашим сайтом.

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

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

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.

Prerequisites

Apache web server.
Sudo privileges.

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

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 4 — Configuring Apache Access Logs

In the access log, you can see what pages are users visiting, the status of their requests, and how long it took to process their requests.

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

%h — 127.0.0.1 — Hostname or IP address of the client that made the request
%l — alice — Remote log name (Name used to log in a user). If not set, the default value will be used —
%u — Alice — Remote username (Username of logged-in user). If not set, the default value will be used —
%t — [06/May/2021:11:26:42 +0200] — Day and time of the request
\»%r\» — «GET / HTTP/1.1» — Actual request
%>s — 200 — Response code
%O — 3477 — Size of the response in bytes

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:

LogFormat «%h %l %u %t \»%r\» %>s %O \»%{Referer}i\» \»%{User-Agent}i\»» combined
The entry in the log file will 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):

\»%{Referer}i\» — «-» — URL of the referer
\»%{User-Agent}i\» — «Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36» — Detailed information about he browser of the user that made the request.

Custom Log Format

You can define your custom log format in the /etc/apache2/apache2.conf using LogFormat directive followed by the actual format of the output and nickname that will be used as format identifier.

For this example, we will create a custom log format named custom that will only print the user’s browser information. The format will look like this:

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

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

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.

Apache has been around since 1995 and is the most important web technology. The majority of businesses nowadays run-on Apache servers. Different servers operate in different ways and have different features and functions. For simple debugging, several servers keep server logs. Understanding how the server works is essential.

All errors encountered by the server while receiving or processing requests are recorded in the Apache error logs. These logs are accessible to admin users, who can troubleshoot them for immediate solutions.

These logs will provide you with useful information about the traffic to your application, errors that occur, and performance. This article will cover Apache web server logs, including log levels, format, and formatting as JSON.

We will cover the following:

  1. What are Apache Logs?
  2. What is the Apache Error Log?
  3. Apache Error Log vs Apache Access Log
  4. Where Do You Find the Apache Error Log?
  5. How Do You Check the Apache Error Log?
  6. Configuring Apache Logs
  7. Apache Error Log Levels
  8. Apache Error Log Format
  9. Apache Request Tracking
  10. Managed Dedicated Servers
  11. Unmanaged Dedicated Servers
  12. Assigning Nicknames
  13. Formatting as JSON
  14. How Do You Clear the Apache Error Log?

What are Apache Logs?

The Apache server keeps a record of all server actions in a text file known as Apache logs. These logs provide useful information about what resources are used and released. Additionally, the logs contain information about who visited those resources and for how long and all related data.

Not only that, but you’ll get all of the details on all of the errors that occurred. The admins can use these logged errors to look into fixing the errors and determining the root cause to eliminate the possibility of the error occurring again.

There isn’t a single Apache logging process. It involves several steps, including saving the logs in a specified area for future reference, analyzing and parsing the logs to extract the relevant information, and producing the graph for a better visual representation. There isn’t a single log type that Apache keeps track of. However, we’ll be concentrating on Apache error logs.

Types of Apache Log

There are two types of logs produced by Apache: Access logs and Error logs.

  1. Access Log
    The access log keeps track of the requests that come into the webserver. This data could include what pages visitors are looking at, the status of requests, and how long it took the server to respond.
  2. Error Log
    The error log records any errors encountered by the web server when processing requests, such as missing files. It also contains server-specific diagnostic information.

What is the Apache Error Log?

If you can’t figure out what’s wrong with your server and it keeps throwing errors, it will become unreliable. We must keep information about the errors affecting the server’s performance for easy and seamless server operation.

As a result, Apache keeps error logs in a specific location. For simple troubleshooting, the server administrator sets up these log files and other details such as file size, error time, type of error, error message, and so on.

The Apache log keeps track of events handled by the Apache web server, such as requests from other computers, Apache responses, and internal Apache server operations.

These logs will continue to be created and stored at that location, making them accessible in the future. You must understand where these errors are saved, how to access them, and how to use the information they provide.

Apache Error Log vs. Apache Access Log

The next thing that people appear to be confused about is the difference between the access log and the error log. Are these two different concepts? Or do they refer to the same thing under different names?

They’re two very different things. The access log is not the same as the error log.

The access log keeps an account of all requests made to the web server, as well as who made them. You can think of it as a geekier version of an event guest log. It keeps track of information like visitor IP addresses, URL requests, responses, and so on.

While the access log may contain information about difficulties that arise, the error log—the subject of our discussion today—is dedicated to logging errors and problems that occur during the server’s operation. You can search for general information about web requests in the access log, but errors should be found in the error log.

Where do you find the Apache Error Log?

Several factors have a role in this:

  • Apache is a cross-platform web server that can run on nearly any operating system. It’ll be difficult enough to figure out which version to download, let alone locate any log files it generates.
  • The majority of Apache installations take place on Unix and Linux systems, which are even more fragmented in terms of where you can find stuff.
  • Apache is highly customizable. While this gives it a lot of flexibility and power, it also makes items more difficult to find because you can put them everywhere.

So, what does it all add up to?

When you Google «where is the Apache error log,» Google could simply pop up a message saying, «No one knows where yours is.» This would save you a lot of clicking and bounce.

However, everything is not lost.

You could look up your operating system’s log file location or the default Apache log file location using Google. Keep in mind that you’ll have to search for your operating system. The ‘/var/log‘ directory is a common destination for log files on *nix systems.

Instead, we did investigate the location of your Apache configuration files. Because these are configurable Apache settings, you can identify the location of the error log (and other logs) once you have that.

For instance, consider the following example of log location configuration:

Update the below log path and log levels in the default configuration file — /etc/apache2/apache2.conf.

ErrorLog "/var/log/apache2/error.log"

By the way, you’re not obligated to name the file «error.log.» Instead, any legal name you provide would suffice. If the specified file already exists, additional log entries will be appended to it.

You can also use a Syslog server to send log messages. Use the Syslog directive instead of a filename.

ErrorLog syslog

There are numerous options for the logging facility and the application name in the Syslog option. Details can be found here.

Finally, you can use a Linux command to redirect logs.

ErrorLog "|/usr/local/bin/httpd_errors"

The pipe character tells Apache that the messages should be piped to the specified command.

Access logs for apache can be found in the following directory on the cPanel server.

/usr/local/apache/logs/access_log

How do you check the Apache Error Log?

How do you go about really checking it once you’ve located it?

You must first understand what it is to understand how it is.

A text file contains the Apache error log. So you can use any text editor or a command-line application like Cat or Tail to open it. These will offer you a quick preview of the contents and allow you to navigate through to find what you need. The entries in the file will be in reverse chronological order.

Let’s say you wish to utilize the «tail» command. In practice, how would you go about doing that?

Easy. To begin, start a shell session.

After that, you type the command:

tail -f /path-to/log

You’ll see the file’s last few entries after running the command above. You’ll also see new entries as they become available.

Since your log file contains errors, it should now be small. However, it could be large—too large to search quickly. In that situation, you might wish to use grep and regex to scan the contents of the error log. Alternatively, you may use a log aggregator to parse and turn the contents into data that you can readily query.

Configuring Apache Logs

The logging framework in Apache is highly flexible, allowing you to change logging behavior globally or for each virtual host. To adjust logging behavior, you can use several directives. The log level and log format directives are two of the most popular directives.

Apache Error Log Levels

It’s no surprise that the Apache error log, like any other log file, uses logging levels.

If you’re unfamiliar with the concept of logging levels, we recommend reading our post on the log levels.

In short, logging levels are labels that can be applied to log entries. The messages transmitted to the log file can then be filtered, thereby changing the verbosity of each message.

The LogLevel directive can be used to specify the desired level, as shown in the following example:

LogLevel warn

The default level is «warn,» although there are a variety of alternative options.

The levels are described as follows in the Apache documentation:

Apache Error Log Levels

If you want to understand more about each level in-depth, go to Apache’s documentation.

Let’s look at how the two logging levels compare. We’ll compare the levels of warning and debug logs.

  1. Warning: You will only receive warning logs if the system is functioning normally but something does not appear to be correct. If these warnings are not addressed promptly, they may result in serious problems over time.
  2. Debug log level, on the other hand, logs practically everything that happens on the server. It might be errors or any other essential notification that you as a website administrator could find useful.

The following command in the main configuration file can be used to enable debug log level.

LogLevel alert rewrite:trace6

Apache Error Log Format

You can also modify the format of log messages. We have been using the default format thus far. The ErrorLogFormat setting controls the message composition.

Let’s try a different setting to see what happens. We are going to utilize this example from the Apache documentation.

ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [client %a] %M"

This is how a request appears right now:

[Thu Jun 09 11:46:18 2022] [fuga:error] [pid 6157:tid 4946] [client 144.110.67.126:20151] You can't copy the port without navigating the haptic SMTP card!
[Thu Jun 09 11:46:18 2022] [pariatur:info] [pid 5946:tid 7137] [client 35.8.11.82:2909] We need to transmit the primary SQL interface!

Let’s go over how to use this format. The format string contains parameters that correspond to fields in a logging event.

The fields we used above are as follows:

Apache Error Log Format

For new connections and requests, you can define alternative formats. When a new client connects to the server, it is called a connection. A request is a communication that asks for something, such as a page or an image.

Apache uses connection and request formats when a new client connects or makes a web request. It records a message indicating that a client has established a connection or made a new request.

Apache Request Tracking

You can go a step further with logging messages for new connections and requests. Every new request or connection will generate a unique identifier in the Apache error log. This parameter can be used to group log entries. For identifiers, use the %L field.

Assigning Nicknames

You can give LogFormat strings nicknames, which you can use with the CustomLog directive to write logs in the format you specify. This allows you to use the same log format across multiple log files without having to change it each time. This is especially beneficial when many virtual hosts are utilizing separate log files.

Let’s say you want to build an example format called «vhost_combined.» Then, using the vhost_combined format, we’ll create a CustomLog directive that writes logs to a file.

LogFormat "%v:%p %h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" vhost_combined
CustomLog /var/log/apache2/vhost.log vhost_combined

Formatting as JSON

If you save your logs as plain text, they’ll be easy to scan if you ever need to read them. This makes it difficult to understand your logs with tools like log management solutions, which require knowledge of how your logs are formatted. The default Apache log format is supported by most log management solutions, but if it isn’t, you should consider adopting a structured format like JSON.

JSON is a lightweight data storage format. JSON holds practically any data type and structure as a set of nestable name/value pairs. JSON is also self-documenting because the key name describes the data it contains. Strings, numbers, booleans, arrays, and null values are among the basic data types supported by JSON.

A LogFormat that saves logs in JSON format looks like this:

LogFormat "{ \"time\":\"%t\", \"remoteIP\":\"%a\", \"host\":\"%V\", \"request\":\"%U\", \"query\":\"%q\", \"method\":\"%m\", \"status\":\"%>s\", \"userAgent\":\"%{User-agent}i\", \"referer\":\"%{Referer}i\" }"

Read must-know tips for JSON logging.

How Do You Clear the Apache Error Log?

Simply put, the log file will get quite large throughout a long period. You won’t need error messages from two years ago at some point. So you’d like to get rid of it to free up some disk space, either by truncating it or backing it up somewhere else.

When it comes to deleting the logs, there’s an interesting problem to solve. The server keeps a handle on the file for writing as long as it is operating. You can’t just open it and start editing it, or back it up and delete it.

Having root access and doing something like this—overwriting the file contents with nothing—might be the simplest method. However, we would recommend making a backup of the file first.

Alternatively, you can follow the instructions for log rotation and piped logs on Apache’s website. These solutions are more complicated, but they are more «proper» and less hacky.

However, regardless of how you approach deleting the logs or logging in general, our advice is to always err on the side of keeping as much information as possible.

Conclusion

The Apache error logs may appear to be simple. More than grepping log files or other ad hoc approaches are required to achieve uptime SLA. You should create a system for storing and analyzing Apache error logs. Tracking and analyzing HTTP error codes, finding outlier IP addresses, listing pages with slow response times, and other metrics that might improve uptime and MTTR.


Atatus

Logs Monitoring and Management

Atatus offers a
Logs Monitoring
solution which is delivered as a fully managed cloud service with minimal setup at any scale that requires no maintenance. It monitors logs from all of your systems and applications into a centralized and easy-to-navigate user interface, allowing you to troubleshoot faster.

We give a cost-effective, scalable method to centralized logging, so you can obtain total insight across your complex architecture. To cut through the noise and focus on the key events that matter, you can search the logs by hostname, service, source, messages, and more. When you can correlate log events with

APM

slow traces and errors, troubleshooting becomes easy.

Try your 14-day free trial of Atatus.

Понравилась статья? Поделить с друзьями:
  • Заведующий поликлиники принял нас быстро где ошибка
  • Журнал ошибок самсунг приложений
  • Журнал ошибок программы
  • Заведующий детского сада лексическая ошибка
  • Журнал ошибок операционной системы