Error log list

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

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

Как читать логи с ошибками сервера

Что такое логи

Это текстовые файлы, которые хранятся на жестком диске сервера. Создаются и заполняются в автоматическом режиме, в хронологическом порядке. В них записываются:

  • системная информация о переданных пользователю данных;
  • сообщения о сбоях и ошибках;
  • протоколирующие данные о посетителях платформы.

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

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Классификация логов

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

  • доступа (access_log) — записывают IP-адрес, время запроса, другую информацию о пользователях;
  • ошибок (error_log) — показывают файлы, в которых выявлены ошибки и классифицируют сбои;
  • FTP-авторизаций — отображают данные о попытках входа по FTP-соединению;
  • загрузки системы — с его помощью выполняется отладка при появлении проблем, в файл записываются основные системные события, включая сбои;
  • основной — содержит информацию о действиях с файерволом, DNS-сервером, ядром системы, FTP-сервисом;
  • планировщика задач — в нем выполняется протоколирование задач, отображаются ошибки при запуске cron;
  • баз данных — хранит подробности о запросах, сбоях, ошибки в логах сервера отображаются наравне с другой важной информацией;
  • хостинговой панели — включает статистику использования ресурсов сервера, время и количество входов в панель, обновление лицензии;
  • веб-сервера — содержит информацию о возникавших ошибках, обращениях;
  • почтового сервера — в нем ведутся записи о входящих и исходящих сообщениях, отклонениях писем.

Записи в системные журналы выполняет установленный софт.

Классификация логов

Зачем нужны логи

Анализ логов сервера — неотъемлемая часть работы системного администратора или веб-разработчика. Обрабатывая их, специалисты получают массу полезных сведений. Используются в следующих целях:

  • поиск ошибок и сбоев в работе системы;
  • выявление вредоносной активности;
  • сбор статистики посещения веб-ресурса.

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

Читайте также

Настройка Iptables для чайников

Как установить и настроить NTP на сервере

Где посмотреть логи

Расположение определяется хостинг-провайдером или настройками установленного софта. На виртуальном хостинге доступ к лог-файлам предоставляется из панели управления хостингом. Если администратор не открыл его для владельца сайта, получить информацию не получится. Но большинство провайдеров разрешают свободно пользоваться журналами и проводить анализ логов сервера. Независимо от разновидности сервера лог-файлы хранятся в текстовом документе. По умолчанию он называется access.log, но настройки позволяют переименовать файл. Это актуально для Nginx, Apache, прокси-разновидностей squid, других типов. Для просмотра их надо скачать и открыть в текстовом редакторе. В качестве альтернативы можно использовать Grep и схожие утилиты. Они позволяют открыть и отфильтровать логи прямо на сервере.

VDS Timeweb арендовать

Как читать логи. Пример

Существует довольно много форматов записи, combined — один из наиболее распространенных. В нем строчка кода может выглядеть так:

%h %l %u %t «%r» %>s %b «%{Referer}i» «%{User-Agent}i»

Директивы имеют следующее значение:

  • %h — IP-адрес, с которого был сделан запрос;
  • %l — длинное имя удаленного хоста;
  • %u — удаленный пользователь, если запрос был сделан аутентифицированным юзером;
  • %t — время запроса к серверу и его часовой пояс;
  • %r — тип и содержимое запроса;
  • %s — код состояния HTTP;
  • %b — количество байт информации, отданных сервером;
  • %{Referer} — URL-источник запроса;
  • %{User-Agent} — HTTP-заголовок.

Еще один пример чтения логов можно посмотреть в статье «Как читать логи сервера».

Опытные веб-мастера для сбора и чтения лог-файлов используют программы-анализаторы. Они позволяют читать логи сервера без значительных временных затрат. Вот некоторые из наиболее востребованных:

  • Analog. Один из самых популярных анализаторов, что во многом объясняется высокой скоростью обработки данных и экономным расходованием системных ресурсов. Хорошо справляется с объемными записями, совместим с любыми ОС.
  • Weblog Expert. Программа доступна в трех вариациях: Lite (бесплатная версия), Professional и Standard (платные релизы). Версии отличаются функциональными возможностями, но каждая позволяет анализировать лог-файлы и создает отчеты в PDF и HTML.
  • SpyLOG Flexolyzer. Простой аналитический инструмент, позволяющий получать отчеты с высокой степенью детализации. Интегрируется c системой статистики SpyLOG, позволяет решать задачи любой сложности.

Логи сервера с ошибками error.log

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

Каждая ошибка в логе сервера error.log отображается с новой строки. Идентифицировав и устранив ее, программист сможет наладить работу сайта. Используя журнал, можно выявить и слабые места веб-платформы. Это простой и удобный инструмент анализа, которым должен уметь пользоваться каждый веб-мастер, системный администратор и программист.

Время прочтения
6 мин

Просмотры 392K

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

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

Основные лог файлы

Все файлы журналов, можно отнести к одной из следующих категорий:

  • приложения;
  • события;
  • службы;
  • системный.

Большинство же лог файлов содержится в директории /var/log.

  • /var/log/syslog или /var/log/messages содержит глобальный системный журнал, в котором пишутся сообщения с момента запуска системы, от ядра Linux, различных служб, обнаруженных устройствах, сетевых интерфейсов и много другого.
  • /var/log/auth.log или /var/log/secure — информация об авторизации пользователей, включая удачные и неудачные попытки входа в систему, а также задействованные механизмы аутентификации.
  • /var/log/dmesg — драйвера устройств. Одноименной командой можно просмотреть вывод содержимого файла. Размер журнала ограничен, когда файл достигнет своего предела, старые сообщения будут перезаписаны более новыми. Задав ключ --level= можно отфильтровать вывод по критерию значимости.

Поддерживаемые уровни журналирования (приоритеты):
   emerg - система неиспользуемая
   alert - действие должно быть произведено немедленно
    crit - условия критичности
     err - условия ошибок
    warn - условия предупреждений
  notice - обычные, но значимые условия
    info - информационный
   debug - отладочные сообщения

(5:520)$ dmesg -l err
[1131424.604352] usb 1-1.1: 2:1: cannot get freq at ep 0x1
[1131424.666013] usb 1-1.1: 1:1: cannot get freq at ep 0x81
[1131424.749378] usb 1-1.1: 1:1: cannot get freq at ep 0x81

  • /var/log/alternatives.log — Вывод программы update-alternatives, в котором находятся символические ссылки на команды или библиотеки по умолчанию.
  • /var/log/anaconda.log — Записи, зарегистрированные во время установки системы.
  • /var/log/audit — Записи, созданные службой аудита auditd.
  • /var/log/boot.log — Информация, которая пишется при загрузке операционной системы.
  • /var/log/cron — Отчет службы crond об исполняемых командах и сообщения от самих команд.
  • /var/log/cups — Все, что связано с печатью и принтерами.
  • /var/log/faillog — Неудачные попытки входа в систему. Очень полезно при проверке угроз в системе безопасности, хакерских атаках, попыток взлома методом перебора. Прочитать содержимое можно с помощью команды faillog.
  • var/log/kern.log — Журнал содержит сообщения от ядра и предупреждения, которые могут быть полезны при устранении ошибок пользовательских модулей встроенных в ядро.
  • /var/log/maillog/ или /var/log/mail.log — Журнал почтового сервера, используемого на ОС.
  • /var/log/pm-powersave.log — Сообщения службы экономии заряда батареи.
  • /var/log/samba/ — Логи файлового сервера Samba, который используется для доступа к общим папкам Windows и предоставления доступа пользователям Windows к общим папкам Linux.
  • /var/log/spooler — Для представителей старой школы, содержит сообщения USENET. Чаще всего бывает пустым и заброшенным.
  • /var/log/Xorg.0.log — Логи X сервера. Чаще всего бесполезны, но если в них есть строки начинающиеся с EE, то следует обратить на них внимание.

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

  • /var/log/yum.log — Для программ установленных с помощью Yum в RedHat Linux.
  • /var/log/emerge.log — Для ebuild-ов установленных из Portage с помощью emerge в Gentoo Linux.
  • /var/log/dpkg.log — Для программ установленных с помощью dpkg в Debian Linux и всем семействе родственных дистрибутивах.

И немного бинарных журналов учета пользовательских сессий.

  • /var/log/lastlog — Последняя сессия пользователей. Прочитать можно командой last.
  • /var/log/tallylog — Аудит неудачных попыток входа в систему. Вывод на экран с помощью утилиты pam_tally2.
  • /var/log/btmp — Еже один журнал записи неудачных попыток входа в систему. Просто так, на всякий случай, если вы еще не догадались где следует искать следы активности взломщиков.
  • /var/log/utmp — Список входов пользователей в систему на данный момент.
  • /var/log/wtmp — Еще один журнал записи входа пользователей в систему. Вывод на экран командой utmpdump.

(5:535)$ sudo utmpdump /var/log/wtmp
[5] [02187] [l0  ] [        ] [4.0.5-gentoo     ] [0.0.0.0     ] [Вт авг 11 16:50:07 2015]
[1] [00000] [~~  ] [shutdown] [4.0.5-gentoo     ] [0.0.0.0     ] [Вт авг 11 16:50:08 2015]
[2] [00000] [~~  ] [reboot  ] [3.18.12-gentoo   ] [0.0.0.0     ] [Вт авг 11 16:50:57 2015]
[8] [00368] [rc  ] [        ] [3.18.12-gentoo   ] [0.0.0.0     ] [Вт авг 11 16:50:57 2015]
[1] [20019] [~~  ] [runlevel] [3.18.12-gentoo   ] [0.0.0.0     ] [Вт авг 11 16:50:57 2015]

И другие журналы

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

  • /var/log/mysql/ — Лог базы данных MySQL.
  • /var/log/httpd/ или /var/log/apache2/ — Лог веб сервера Apache, журнал доступа находится в access_log, а ошибки — в error_log.
  • /var/log/lighthttpd/ — Лог веб сервера lighttpd.

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

  • ~/.xsession-errors — Вывод stderr графических приложений X11.

Initializing  "kcm_input" :  "kcminit_mouse"
Initializing  "kcm_access" :  "kcminit_access"
Initializing  "kcm_kgamma" :  "kcminit_kgamma"
QXcbConnection: XCB error: 3 (BadWindow), sequence: 181, resource id: 10486050, major code: 20 (GetProperty), minor code: 0
kf5.kcoreaddons.kaboutdata: Could not initialize the equivalent properties of Q*Application: no instance (yet) existing.
QXcbConnection: XCB error: 3 (BadWindow), sequence: 181, resource id: 10486050, major code: 20 (GetProperty), minor code: 0
Qt: Session management error: networkIdsList argument is NULL

  • ~/.xfce4-session.verbose-log — Сообщения рабочего стола XFCE4.

Чем просматривать — lnav

Почти все знают об утилите less и команде tail -f. Также для этих целей сгодится редактор vim и файловый менеджер Midnight Commander. У всех есть свои недостатки: less неважно обрабатывает журналы с длинными строками, принимая их за бинарники. Midnight Commander годится только для беглого просмотра, когда нет необходимости искать по сложному шаблону и переходить помногу взад и вперед между совпадениями. Редактор vim понимает и подсвечивает синтаксис множества форматов, но если журнал часто обновляется, то появляются отвлекающие внимания сообщения об изменениях в файле. Впрочем это легко можно обойти с помощью <:view /path/to/file>.

Недавно я обнаружил еще одну годную и многообещающую, но слегка еще сыроватую, утилиту — lnav, в расшифровке Log File Navigator.

Установка пакета как обычно одной командой.

$ aptitude install lnav #Debian/Ubuntu/LinuxMint
$ yum install lnav #RedHat/CentOS
$ dnf install lnav #Fedora
$ emerge -av lnav #Gentoo, нужно добавить в файл package.accept_keywords
$ yaourt -S lnav #Arch

Навигатор журналов lnav понимает ряд форматов файлов.

  • Access_log веб сервера.
  • CUPS page_log
  • Syslog
  • glog
  • dpkg.log
  • strace
  • Произвольные записи с временными отметками
  • gzip, bzip
  • Журнал VMWare ESXi/vCenter

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

(5:471)$ sudo lnav /var/log/pm-powersave.log /var/log/pm-suspend.log

Программа умеет напрямую открывать архивный файл.

(5:471)$ lnav -r /var/log/Xorg.0.log.old.gz

Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу <i>. Это с моего syslog-а.

Mon May 02 20:25:00        123 normal         3 errors         0 warnings         0 marks
Mon May 02 22:40:00          2 normal         0 errors         0 warnings         0 marks
Mon May 02 23:25:00         10 normal         0 errors         0 warnings         0 marks
Tue May 03 07:25:00         96 normal         3 errors         0 warnings         0 marks
Tue May 03 23:50:00         10 normal         0 errors         0 warnings         0 marks
Wed May 04 07:40:00         96 normal         3 errors         0 warnings         0 marks
Wed May 04 08:30:00          2 normal         0 errors         0 warnings         0 marks
Wed May 04 10:40:00         10 normal         0 errors         0 warnings         0 marks
Wed May 04 11:50:00        126 normal         2 errors         1 warnings         0 marks

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

Использованные материалы

  1. lnav — An Advanced Log File viewer for Linux
  2. What Are Linux Logs? How to View Them, Most Important Directories, and More
  3. Как посмотреть логи в Linux

Просмотр и анализ логов сайта на Linux сервере

Содержание:

  • Важные логи сайта
  • Расположение логов
  • Чтение записей в логах
  • Просмотр с помощью команды tail
  • Просмотр с помощью ISPManager
  • Программы для анализа логов
  • Ведение логов медленных запросов сервера
  • Ведение логов с помощью Logrotate

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

Важные логи сайта

  • Access.log — логи посещений пользователей и ботов. Позволяет составить более точную и подробную статистику, нежели сторонние ресурсы, выполняющие внешнее сканирование сайта и отправляющие ряд ненужных запросов серверу. Благодаря данному логу можно получить информацию об используемом браузере и IP-адрес посетителя, данные о местонахождении клиента (страна и город) и многое другое. Стоит обратить внимание, если сайт имеет высокую посещаемость, то анализ логов сервера потребует больше времени. Поэтому для составления статистики стоит использовать специализированные программы (анализаторы).
  • Error.log — программные ошибки сервера. Стоит внимательно отнестись к анализу данного лога, ведь боты поисковиков, сканируя, получают все данные о работе сайта. При обнаружении большого количества ошибок, сайт может попасть под санкции поисковых систем. В свою очередь из записей данного журнала можно узнать точную дату и время ошибки, IP-адрес получателя, тип и описание ошибки.
  • Slow.log (название зависит от используемой оболочки сервера) — в данный журнал записываются медленные запросы сервера. Так принято обозначать запросы с повышенным порогом задержки, выданные пользователю. Этот журнал позволяет выявить слабые места сервера и исправить проблему. Ниже будет рассмотрен способ включить ведение данного лога на разных типах серверов, а также настройка задержки, с которой записи будут заноситься в файл.

Расположение логов

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

Стандартные пути до Error.log

Nginx

/var/log/nginx/error.log

Php-Fpm

/var/log/php-fpm/error.log

Apache (CentOS)

/var/log/httpd/error_log

Apache (Ubuntu, Debian)

/var/log/apache2/error_log

Стандартные пути до Access.log

Nginx

/var/log/nginx/access.log

Php-Fpm

/var/log/php-fpm/access.log

Apache (CentOS)

/var/log/httpd/access_log

Apache (Ubuntu, Debian)

/var/log/apache2/access_log

Чтение записей в логах

Записи в логах имеют структуру: одно событие – одна строка.

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

Примеры записей

Error.log

[Sat Sep 1 15:33:40.719615 2019] [:error] [pid 10706] [client 66.249.66.61:60699] PHP Notice: Undefined variable: moduleclass_sfx in /var/data/www/site.ru/modules/contacts/default.php on line 14

В приведенном примере:

  • [Sat Sep 1 15:33:40.719615 2019] — дата и время события.
  • [:error] [pid 10706] — ошибка и её тип.
  • [client 66.249.66.61:60699] — IP-адрес подключившегося клиента.
  • PHP Notice: Undefined variable: moduleclass_sfx in — событие PHP Notice. В данной ситуации — обнаружена неизвестная переменная.
  • /var/data/www/site.ru/modules/contacts/default.php on line 14 — путь и номер строки в проблемном файле.

Access.log

194.61.0.6 – alex [10/Oct/2019:15:32:22 -0700] "GET /apache_pb.gif HTTP/1.0" 200 5396 "http://www.mysite/myserver.html" "Mozilla/4.08 [en] (Win98; I ;Nav)"

В приведенном примере:

  • 194.61.0.6 — IP-адрес пользователя.
  • alex — если пользователь зарегистрирован в системе, то в логах будет указан идентификатор.
  • [10/Oct/2019:15:32:22 -0700]— дата и время записи.
  • «GET /apache_pb.gif HTTP/1.0» — «GET» означает, что определённый документ со страницы сайта был отправлен пользователю. Существует команда «POST», наоборот отправляет конкретные данные (комментарий или любое другое сообщение) на сервер . Далее указан извлечённый документ «Apache_pb.gif», а также использованный протокол «HTTP/1.0».
  • 200 5396 — код и количество байтов документа, которые были возвращены сервером.
  • «http://www. www.mysite/myserver.html»— страница, с которой был произведён запрос на извлечение документа «Apache_pb.gif».
  • «Mozilla/4.08 [en] (Win98; I ;Nav)» — данные о пользователе, которой произвёл запрос (используемый браузер и операционная система).

Просмотр логов сервера с помощью команды tail

Выполнить просмотр логов в Linux можно с помощью команды tail. Данный инструмент позволяет смотреть записи в логах, выводя последние строки из файла. По умолчанию tail выводит 10 строк.

Первый вариант использования Tail

tail -f /var/log/syslog

Аргумент «-f» позволяет команде делать просмотр событий в режиме реального времени, в ожидании новых записей в лог файлах. Для прерывания процесса следует нажать сочетание клавиш «Ctrl+C».

На место переменной «/var/log/syslog» в примере следует подставить актуальный адрес до нужных системных журналов.

Второй вариант использования Tail

tail -F /var/log/syslog

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

Если будет использоваться аргумент «-f», команда продолжит отслеживание старого, переименованного журнала. Данный метод делает невозможным просмотр логов в реальном времени, поскольку файл более не актуален.

При использовании аргумента «-F», команда, после окончания записи старого журнала, перейдёт к чтению нового файла с логами. В таком случае просмотр логов в режиме реального времени продолжится.

Аналог команды Tail

tailf /var/log/syslog

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

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

Изменение стандартного количества строк для вывода

Как и отмечалось выше, по умолчанию выводится 10 строк. Если требуется увеличить или уменьшить их количество, в команду добавляется аргумент «-n» и необходимое число строк.

Пример:

tail -f -n 100 /var/log/syslog

При использовании данной команды будут показаны последние 100 строк журнала.

Просмотр логов с помощью ISPManager

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

  1. На главной странице, в панели инструментов «WWW» нужно нажать на вкладку «Журналы».
    Просмотр логов с помощью ISPManager
  2. ISPManager выдаст журналы посещений и серверных ошибок в виде:
    • ru.access.log;
    • ru.error.log.*

    * Вместо «newdomen.ru» из примера в выдаче будет название актуального домена.

    Открыть файл лога можно, нажав на «Посмотреть» в верхнем меню.

  3. Для просмотра всех записей журнала, необходимо нажать на «Скачать» и сохранить файл на локальный носитель.
    Просмотр логов с помощью ISPManager
  4. Более старые версии логов можно найти во вкладке «Архив».
    Просмотр логов с помощью ISPManager

Программы для анализа логов

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

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

Статические программы

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

WebLog ExpertWebLog Expert

Возможности
  • Предоставление информации об активность сайта, количестве посетителей, доступ к файлам, URL страницы, ссылающиеся страницы, информацию о пользователе (браузер и операционная система).
  • Создание отчётов в формате HTML (.html), PDF (.pdf), CSV (.csv).
  • Поддерживает анализ логов Nginx, Apache, ISS.
  • Чтение файлов даже в архивах ZIP (.zip), GZ (.gz).

Web Log Explorer

Web Log Explorer
Возможности
  • Создание многоуровневых отчётов, включающих количество посетителей, маршруты пользователей по сайту, местоположение хостов (страна и город), указанные в поисковике ключевые слова.
  • Поддержка более 43 форматов логов.
  • Возможность прямой загрузки логов с FTP, HTTP сервера.
  • Чтение архивированных журналов.

Программы для анализа в режиме реального времени

Эти инструменты встраиваются в программную среду сервера, анализируют данные в реальном времени и записывают непрерывный отчёт.

GoAccess

GoAccess
Возможности
  • Автоматическая генерация отчёта в формате HTML (.html), JSON (.json), CSV (.csv).
  • При подключении к серверу через SSH, возможен анализ в браузере и в терминале
  • Поддержка почти всех форматов (Apache, Nginx, Amazon S3, Elastic Load Balancing, CloudFront и др.).

Logstash

Logstash
Возможности
  • Постоянная генерация отчёта в файл JSON (.json).
  • Получение и анализ информации из нескольких источников.
  • Возможность пересылать журналы с помощью Filebeat.
  • Поддержка анализа системных журналов.
  • Поддерживается большое количество форматов: от Apache до Log4j (Java).

Ведения логов медленных запросов сервера

Анализ данного лога позволяет определить на какие типы запросов сервер отвечает долго. В идеале задержка должна составлять не более 1 секунды.

На некоторых типах оболочек (MySQL, PHP-FPM) ведение данного лога по умолчанию отключено. Процесс запуска и ведения зависит от сервера.

MySQL

Если сервер управляется с помощью MySQL, то необходимо создать каталог и сам файл для ведения журнала с помощью команд:

mkdir /var/log/mysql
touch /var/log/mysql/mysql-slow.log

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

chown mysql:mysql /var/log/mysql/mysql-slow.log

После выполнения предыдущих действий, нужно совершить вход в командную строку MySQL под учётной записью суперпользователя:

mysql -uroot -p

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

> SET GLOBAL slow_query_log = 'ON';

> SET GLOBAL slow_launch_time = 2;

> SET GLOBAL slow_query_log_file = '/var/log/mysql/mysql-slow.log';

> FLUSH LOGS;

В примере:

  • slow_query_log — запускает ведение журналов медленных запросов.
  • slow_launch_time — указывает максимальную задержку отклика, после которой статистика запроса попадёт в журнал. В данном случае запись в логи происходит при преодолении откликом порога 2 секунды.
  • slow_query_log_file — задаёт путь до используемого журнала.

Проверить статус и параметры ведения лога медленных запросов можно командой:

> SHOW VARIABLES LIKE '%slow%';

Выход из консоли MySQL выполняется командой:

> exit

После выполнения всех предыдущих действий, можно просмотреть логи сервера. Для этого в терминале вводится:

tail -f /var/log/mysql/mysql-slow.log

PHP-FPM

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

vi /etc/php-fpm.d/www.conf

Далее нужно найти строки:

  • request_slowlog_timeout = 10s — параметр, позволяющий указать задержку, с которой запись о длительном запросе попадёт в журнал.
  • slowlog = /var/log/php-fpm/www-slow.log — параметр, указывающий путь до актуального файла логирования (.log).

После применения изменений, необходимо перезагрузить сервер PHP-FPM. Для этого в консоль вводится команда:

systemctl restart php-fpm

Просмотр логов запускается командой:

tail -f /var/log/php-fpm/www-slow.log

Анализ логов медленных запросов

Логи медленных запросов могут за незначительное время вырасти до огромных размеров. Для сортировки и отображения повторяющихся запросов рекомендуется использовать программу MySQLDumpSlow.

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

mysqldumpslow местонахождение/файла

Ведение логов в Logrotate

На больших ресурсах журналы могут достигать огромных размеров, поэтому нужно своевременно архивировать или очищать логи. С помощью утилиты Logrotate можно управлять ведением журналов: настроить период ротации (архивирование старого журнала и создание нового), период и количество хранения журналов и многое другое.

Изначально программа отсутствует в системе. Ниже приведены команды для инсталляции Logrotate из официальных репозиториев.

Ubuntu, Debian:

sudo apt install logrotate

CentOS:

sudo yum install logrotate

После установки необходимо проверить путь для будущих конфигурационных файлов. Для правильной работы они должны находится в папке «logrotate.d». Проверить данный параметр можно открыв конфигурационный файл  командой:

nano /etc/logrotate.conf

В директории «RPM packages drop log rotation information into this directory» должна присутствовать строка:

include /etc/logrotate.d

Теперь создаётся конфигурационный файл «rsyslog.conf». В нём будет находиться конфигурацию по работе с логами. Для создания файла в терминале вводится команда:

sudo nano /etc/logrotate.d/rsyslog.conf

В окне терминала откроется текстовой редактор. Теперь нужно внести конфигурацию, как указано в образце. В качестве примера будет использоваться журнал посещений «Access.log» (Nginx).

/var/log/nginx/access.log {
daily
rotate 3
size 500M
compress
delaycompress
}

Теперь остаётся только запустить Logrotate. Для этого вводится команда:

sudo logrotate -d /etc/logrotate.d/rsyslog.conf

Для проверки правильности работы программы в терминале можно ввести команду:

ls /var/cron.daily/

In this tutorial, you will learn everything you need to know about logging in
NGINX and how it can help you troubleshoot and quickly resolve any problem you
may encounter on your web server. We will discuss where the logs are stored and
how to access them, how to customize their format, and how to centralize them in
one place with Syslog or a log management service.

Here’s an outline of what you will learn by following through with this tutorial:

  • Where NGINX logs are stored and how to access them.
  • How to customize the NGINX log format and storage location to fit your needs.
  • How to utilize a structured format (such as JSON) for your NGINX logs.
  • How to centralize NGINX logs through Syslog or a managed cloud-based service.

Prerequisites

To follow through with this tutorial, you need the following:

  • A Linux server that includes a non-root user with sudo privileges. We tested
    the commands shown in this guide on an Ubuntu 20.04 server.
  • The
    NGINX web server installed
    and enabled on your server.

🔭 Want to centralize and monitor your NGINX logs?

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

Step 1 — Locating the NGINX log files

NGINX writes logs of all its events in two different log files:

  • Access log: this file contains information about incoming requests and
    user visits.
  • Error log: this file contains information about errors encountered while
    processing requests, or other diagnostic messages about the web server.

The location of both log files is dependent on the host operating system of the
NGINX web server and the mode of installation. On most Linux distributions, both
files will be found in the /var/log/nginx/ directory as access.log and
error.log, respectively.

A typical access log entry might look like the one shown below. It describes an
HTTP GET request to the server for a favicon.ico file.

Output

217.138.222.101 - - [11/Feb/2022:13:22:11 +0000] "GET /favicon.ico HTTP/1.1" 404 3650 "http://135.181.110.245/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36" "-"

Similarly, an error log entry might look like the one below, which was generated
due to the inability of the server to locate the favicon.ico file that was
requested above.

Output

2022/02/11 13:12:24 [error] 37839#37839: *7 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 113.31.102.176, server: _, request: "GET /favicon.ico HTTP/1.1", host: "192.168.110.245:80"

In the next section, you’ll see how to view both NGINX log files from the
command line.

Step 2 — Viewing the NGINX log files

Examining the NGINX logs can be done in a variety of ways. One of the most
common methods involves using the tail command to view logs entries in
real-time:

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

You will observe the following output:

Output

107.189.10.196 - - [14/Feb/2022:03:48:55 +0000] "POST /HNAP1/ HTTP/1.1" 404 134 "-" "Mozila/5.0"
35.162.122.225 - - [14/Feb/2022:04:11:57 +0000] "GET /.env HTTP/1.1" 404 162 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0"
45.61.172.7 - - [14/Feb/2022:04:16:54 +0000] "GET /.env HTTP/1.1" 404 197 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"
45.61.172.7 - - [14/Feb/2022:04:16:55 +0000] "POST / HTTP/1.1" 405 568 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36"
45.137.21.134 - - [14/Feb/2022:04:18:57 +0000] "GET /dispatch.asp HTTP/1.1" 404 134 "-" "Mozilla/5.0 (iPad; CPU OS 7_1_2 like Mac OS X; en-US) AppleWebKit/531.5.2 (KHTML, like Gecko) Version/4.0.5 Mobile/8B116 Safari/6531.5.2"
23.95.100.141 - - [14/Feb/2022:04:42:23 +0000] "HEAD / HTTP/1.0" 200 0 "-" "-"
217.138.222.101 - - [14/Feb/2022:07:38:40 +0000] "GET /icons/ubuntu-logo.png HTTP/1.1" 404 197 "http://168.119.119.25/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
217.138.222.101 - - [14/Feb/2022:07:38:42 +0000] "GET /favicon.ico HTTP/1.1" 404 197 "http://168.119.119.25/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
217.138.222.101 - - [14/Feb/2022:07:44:02 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
217.138.222.101 - - [14/Feb/2022:07:44:02 +0000] "GET /icons/ubuntu-logo.png HTTP/1.1" 404 197 "http://168.119.119.25/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"

The tail command prints the last 10 lines from the selected file. The -f
option causes it to continue displaying subsequent lines that are added to the
file in real-time.

To examine the entire contents of an NGINX log file, you can use the cat
command or open it in your text editor:

sudo cat /var/log/nginx/error.log

If you want to filter the lines that contain a specific term, you can use the
grep command as shown below:

sudo grep "GET /favicon.ico" /var/log/nginx/access.log

The command above will print all the lines that contain GET /favicon.ico so we
can see how many requests were made for that resource.

Step 3 — Configuring NGINX access logs

The NGINX access log stores data about incoming client requests to the server
which is beneficial when deciphering what users are doing in the application,
and what resources are being requested. In this section, you will learn how to
configure what data is stored in the access log.

One thing to keep in mind while following through with the instructions below is
that you’ll need to restart the nginx service after modifying the config file
so that the changes can take effect.

sudo systemctl restart nginx

Enabling the access log

The NGINX access Log should be enabled by default. However, if this is not the
case, you can enable it manually in the Nginx configuration file
(/etc/nginx/nginx.conf) using the access_log directive within the http
block.

Output

http {
  access_log /var/log/nginx/access.log;
}

This directive is also applicable in the server and location configuration
blocks for a specific website:

Output

server {
   access_log /var/log/nginx/app1.access.log;

  location /app2 {
    access_log /var/log/nginx/app2.access.log;
  }
}

Disabling the access log

In cases where you’d like to disable the NGINX access log, you can use the
special off value:

You can also disable the access log on a virtual server or specific URIs by
editing its server or location block configuration in the
/etc/nginx/sites-available/ directory:

Output

server {
  listen 80;

  access_log off;

  location ~* .(woff|jpg|jpeg|png|gif|ico|css|js)$ {
    access_log off;
  }
}

Logging to multiple access log files

If you’d like to duplicate the access log entries in separate files, you can do
so by repeating the access_log directive in the main config file or in a
server block as shown below:

Output

access_log /var/log/nginx/access.log;
access_log /var/log/nginx/combined.log;

Don’t forget to restart the nginx service afterward:

sudo systemctl restart nginx

Explanation of the default access log format

The access log entries produced using the default configuration will look like
this:

Output

127.0.0.1 alice Alice [07/May/2021:10:44:53 +0200] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4531.93 Safari/537.36"

Here’s a breakdown of the log message above:

  • 127.0.0.1: the IP address of the client that made the request.
  • alice: remote log name (name used to log in a user).
  • Alice: remote username (username of logged-in user).
  • [07/May/2021:10:44:53 +0200] : date and time of the request.
  • "GET / HTTP/1.1" : request method, path and protocol.
  • 200: the HTTP response code.
  • 396: the size of the response in bytes.
  • "-": the IP address of the referrer (- is used when the it is not
    available).
  • "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4531.93 Safari/537.36"
    detailed user agent information.

Step 4 — Creating a custom log format

Customizing the format of the entries in the access log can be done using the
log_format directive, and it can be placed in the http, server or
location blocks as needed. Here’s an example of what it could look like:

Output

log_format custom '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"';

This yields a log entry in the following format:

Output

217.138.222.109 - - [14/Feb/2022:10:38:35 +0000] "GET /favicon.ico HTTP/1.1" 404 197 "http://192.168.100.1/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"

The syntax for configuring an access log format is shown below. First, you need
to specify a nickname for the format that will be used as its identifier, and
then the log format string that represents the details and formatting for each
log message.

Output

log_format <nickname> '<formatting_variables>';

Here’s an explanation of each variable used in the custom log format shown
above:

  • $remote_addr: the IP address of the client
  • $remote_user: information about the user making the request
  • $time_local: the server’s date and time.
  • $request: actual request details like path, method, and protocol.
  • $status: the response code.
  • $body_bytes_sent: the size of the response in bytes.
  • $http_referer: the IP address of the HTTP referrer.
  • $http_user_agent: detailed user agent information.

You may also use the following variables in your custom log format
(see here for the complete list):

  • $upstream_connect_time: the time spent establishing a connection with an
    upstream server.
  • $upstream_header_time: the time between establishing a connection and
    receiving the first byte of the response header from the upstream server.
  • $upstream_response_time: the time between establishing a connection and
    receiving the last byte of the response body from the upstream server.
  • $request_time: the total time spent processing a request.
  • $gzip_ratio: ration of gzip compression (if gzip is enabled).

After you create a custom log format, you can apply it to a log file by
providing a second parameter to the access_log directive:

Output

access_log /var/log/nginx/access.log custom;

You can use this feature to log different information in to separate log files.
Create the log formats first:

Output

log_format custom '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer"';
log_format agent "$http_user_agent";

Then, apply them as shown below:

Output

access_log /var/log/nginx/access.log custom;
access_log /var/log/nginx/agent_access.log agent;

This configuration ensures that user agent information for all incoming requests
are logged into a separate access log file.

Step 5 — Formatting your access logs as JSON

A common way to customize NGINX access logs is to format them as JSON. This is
quite straightforward to achieve by combining the log_format directive with
the escape=json parameter introduced in Nginx 1.11.8 to escape characters that
are not valid in JSON:

Output

log_format custom_json escape=json
  '{'
    '"time_local":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"remote_user":"$remote_user",'
    '"request":"$request",'
    '"status": "$status",'
    '"body_bytes_sent":"$body_bytes_sent",'
    '"request_time":"$request_time",'
    '"http_referrer":"$http_referer",'
    '"http_user_agent":"$http_user_agent"'
  '}';

After applying the custom_json format to a log file and restarting the nginx
service, you will observe log entries in the following format:

{
  "time_local": "14/Feb/2022:11:25:44 +0000",
  "remote_addr": "217.138.222.109",
  "remote_user": "",
  "request": "GET /icons/ubuntu-logo.png HTTP/1.1",
  "status": "404",
  "body_bytes_sent": "197",
  "request_time": "0.000",
  "http_referrer": "http://192.168.100.1/",
  "http_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"
}

Step 6 — Configuring NGINX error logs

Whenever NGINX encounters an error, it stores the event data in the error log so
that it can be referred to later by a system administrator. This section will
describe how to enable and customize the error logs as you see fit.

Enabling the error log

The NGINX error log should be enabled by default. However, if this is not the
case, you can enable it manually in the relevant NGINX configuration file
(either at the http, server, or location levels) using the error_log
directive.

Output

error_log /var/log/nginx/error.log;

The error_log directive can take two parameters. The first one is the location
of the log file (as shown above), while the second one is optional and sets the
severity level of the log. Events with a lower severity level than set one will
not be logged.

Output

error_log /var/log/nginx/error.log info;

These are the possible levels of severity (from lowest to highest) and their
meaning:

  • debug: messages used for debugging.
  • info: informational messages.
  • notice: a notable event occurred.
  • warn: something unexpected happened.
  • error: something failed.
  • crit: critical conditions.
  • alert: errors that require immediate action.
  • emerg: the system is unusable.

Disabling the error log

The NGINX error log can be disabled by setting the error_log directive to
off or by redirecting it to /dev/null:

Output

error_log off;
error_log /dev/null;

Logging errors into multiple files

As is the case with access logs, you can log errors into multiple files, and you
can use different severity levels too:

Output

error_log /var/log/nginx/error.log info;
error_log /var/log/nginx/emerg_error.log emerg;

This configuration will log every event except those at the debug level event
to the error.log file, while emergency events are placed in a separate
emerg_error.log file.

Step 7 — Sending NGINX logs to Syslog

Apart from logging to a file, it’s also possible to set up NGINX to transport
its logs to the syslog service especially if you’re already using it for other
system logs. Logging to syslog is done by specifying the syslog: prefix to
either the access_log or error_log directive:

Output

error_log  syslog:server=unix:/var/log/nginx.sock debug;
access_log syslog:server=[127.0.0.1]:1234,facility=local7,tag=nginx,severity=info;

Log messages are sent to a server which can be specified in terms of a domain
name, IPv4 or IPv6 address or a UNIX-domain socket path.

In the example above, error log messages are sent to a UNIX domain socket at the
debug logging level, while the access log is written to a syslog server with
an IPv4 address and port 1234. The facility= parameter specifies the type of
program that is logging the message, the tag= parameter applies a custom tag
to syslog messages, and the severity= parameter sets the severity level of
the syslog entry for access log messages.

For more information on using Syslog to manage your logs, you can check out our
tutorial on viewing and configuring system logs on
Linux.

Step 8 — Centralizing your NGINX logs

In this section, we’ll describe how you can centralize your NGINX logs in a log
management service through Vector, a
high-performance tool for building observability pipelines. This is a crucial
step when administrating multiple servers so that you can monitor all your logs
in one place (you can also centralize your logs with an Rsyslog
server).

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. For example, 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
$ sudo apt install vector

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

You should observe that it is active and running:

Output

● 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

Afterward, change into a root shell and append your Logtail vector configuration
for NGINX 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.

sudo -s
$ wget -O ->> /etc/vector/vector.toml 
    https://logtail.com/vector-toml/nginx/<your_logtail_source_token>

Then restart the vector service:

sudo systemctl restart vector

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

Conclusion

In this tutorial, you learned about the different types of logs that the NGINX
web server keeps, where you can find them, how to understand their formatting.
We also discussed how to create your own custom log formats (including a
structured JSON format), and how to log into multiple files at once. Finally, we
demonstrated the process of sending your logs to Syslog or a log management
service so that you can monitor them all in one place.

Thanks for reading, and happy logging!

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

Share on Twitter

Share on Facebook

Share via e-mail

Next article

How to Get Started with Logging in Node.js

Learn how to start logging with Node.js and go from basics to best practices in no time.

Licensed under CC-BY-NC-SA

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

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.

Over the decades we have been reading the MySQL error log from the server system file, if there are any issues in MySQL or any unknown restart happened , generally we look at the mysql error log.

By default MySQL error log can be found in the default path /var/log/mysqld.log , or it can be explicitly configured using the variable log_error.

Few drawbacks using MySQL error log as FILE

  • Possibility of missing genuine errors while reading lengthy information.
  • Filtering of errors for the particular date and timeframes.
  • Cannot provide the DB server access to developers because of fear of mishandling DB servers.

To overcome the above issues , from MySQL 8.0.22 we can access the error-log from the performance_schema.error_log table.

Granting the SELECT privilege for the error_log table will provide the read access to error log contents using a simple SQL queries for dev teams.

For demo purpose i have installed latest MySQL 8.0.23 in our test environment.

mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.23    |
+-----------+
1 row in set (0.00 sec)

Table structure

mysql> show create table performance_schema.error_logG
*************************** 1. row ***************************
       Table: error_log
Create Table: CREATE TABLE `error_log` (
  `LOGGED` timestamp(6) NOT NULL,
  `THREAD_ID` bigint unsigned DEFAULT NULL,
  `PRIO` enum('System','Error','Warning','Note') NOT NULL,
  `ERROR_CODE` varchar(10) DEFAULT NULL,
  `SUBSYSTEM` varchar(7) DEFAULT NULL,
  `DATA` text NOT NULL,
  PRIMARY KEY (`LOGGED`),
  KEY `THREAD_ID` (`THREAD_ID`),
  KEY `PRIO` (`PRIO`),
  KEY `ERROR_CODE` (`ERROR_CODE`),
  KEY `SUBSYSTEM` (`SUBSYSTEM`)
) ENGINE=PERFORMANCE_SCHEMA DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

Overview to the columns

LOGGED

LOGGED corresponds to the time field of error events occurred , the time values which are stored in the error log table are displayed according to the log_timestamps system variable i.e UTC by default.

we can change the timestamp value by changing log_timestamps variable according to our time zones.

THREAD_ID

It is a MySQL thread ID similar to PROCESSLIST_ID , the thread_id is displayed for events occurred by foreground MySQL threads, for background threads the value be 0.

PRIO

The event priority the permitted values are SystemErrorWarningNote.

ERROR_CODE

Displays the MySQL error codes.

SUBSYSTEM

The subsystem in which the event occurred, example SERVER,INNODB.

DATA

The text representation of the error event.

Variables controlling error logging

Below are the major variables controls the error logging , which defines the output of the error log.

mysql> show global variables like 'log_error%';
+----------------------------+----------------------------------------+
| Variable_name              | Value                                  |
+----------------------------+----------------------------------------+
| log_error                  | /var/log/mysqld.log                    |
| log_error_services         | log_filter_internal; log_sink_internal |
| log_error_suppression_list |                                        |
| log_error_verbosity        | 2                                      |
+----------------------------+----------------------------------------+
  • log_error – This variable defines the path of the MySQL error log.
  • log_error_services – This variable controls which log components to enable for error logging ,by default the values are set to log_filter_internal and log_sink_internal.
  • log_filter_internal: This value provides error log filtering based on the log event priority and error code, in combination with the log_error_verbosity and log_error_suppression_list system variables.
  • log_sink_internal: This value defines the traditional error log output format.
  • log_error_suppression_list – This variable helps to filter or ignore the errors, information and warnings which is not worthy or which creates unnecessary noise in the error log.

we can list of one or more comma-separated values indicating the error codes which we need to suppress. Error codes can be specified in symbolic or numeric form.

Example:

Suppose if we insist to filter out the below warning message from error log:

2021-03-26T09:40:40.109075Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.

log_error_suppression_list takes effect based on the log_error_verbosity value defined

mysql> set global log_error_suppression_list='MY-010068';
Query OK, 0 rows affected (0.00 sec)

mysql> show global variables like 'log_error%';
+----------------------------+----------------------------------------+
| Variable_name              | Value                                  |
+----------------------------+----------------------------------------+
| log_error                  | /var/log/mysqld.log                    |
| log_error_services         | log_filter_internal; log_sink_internal |
| log_error_suppression_list | MY-010068                       |
| log_error_verbosity        | 2                                      |
+----------------------------+----------------------------------------+
4 rows in set (0.00 sec)

To persist the value in CNF

[mysqld] 
log_error_verbosity=2 # error and warning messages only #
log_error_suppression_list='MY-010068'

log_error_verbosity

This variables specifies the verbosity of events which will be logged in the error log , permitted values from 1 to 3. default is 2.

log_error_verbosity Value Permitted Message Priorities
1 ERROR
2 ERRORWARNING
3 ERRORWARNINGINFORMATION

Now let us query the performance_schema.error_log table

mysql> SELECT * FROM performance_schema.error_logG
*************************** 1. row ***************************
    LOGGED: 2021-01-18 09:56:33.800985
 THREAD_ID: 0
      PRIO: System
ERROR_CODE: MY-013169
 SUBSYSTEM: Server
      DATA: /usr/sbin/mysqld (mysqld 8.0.23) initializing of server in progress as process 6335
*************************** 2. row ***************************
    LOGGED: 2021-01-18 09:56:33.818823
 THREAD_ID: 1
      PRIO: System
ERROR_CODE: MY-013576
 SUBSYSTEM: InnoDB
      DATA: InnoDB initialization has started.
*************************** 3. row ***************************
    LOGGED: 2021-01-18 09:56:40.454929
 THREAD_ID: 0
      PRIO: System
ERROR_CODE: MY-011323
 SUBSYSTEM: Server
      DATA: X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
*************************** 4. row ***************************
    LOGGED: 2021-02-15 06:00:28.384059
 THREAD_ID: 0
      PRIO: System
ERROR_CODE: MY-013172
 SUBSYSTEM: Server
      DATA: Received SHUTDOWN from user <via user signal>. Shutting down mysqld (Version: 8.0.23).
*************************** 5. row ***************************
    LOGGED: 2021-02-15 06:00:29.583157
 THREAD_ID: 0
      PRIO: System
ERROR_CODE: MY-010910
 SUBSYSTEM: Server
      DATA: /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.23)  MySQL Community Server - GPL.
*************************** 6. row ***************************
    LOGGED: 2021-03-25 06:48:20.350948
 THREAD_ID: 376
      PRIO: Error
ERROR_CODE: MY-012640
 SUBSYSTEM: InnoDB
      DATA: Error number 28 means 'No space left on device'
*************************** 7. row ***************************
    LOGGED: 2021-03-25 06:48:20.416039
 THREAD_ID: 376
      PRIO: Warning
ERROR_CODE: MY-012145
 SUBSYSTEM: InnoDB
      DATA: Error while writing 4194304 zeroes to ./sbtest/sbtest5.ibd starting at offset 1107296256
*************************** 8. row ***************************
    LOGGED: 2021-03-25 06:48:20.434689
 THREAD_ID: 376
      PRIO: Error
ERROR_CODE: MY-013132
 SUBSYSTEM: Server
      DATA: The table 'sbtest5' is full!

with simple SQL queries , we can filter the logs based on priority

mysql> SELECT * FROM performance_schema.error_log WHERE PRIO='error'G
*************************** 1. row ***************************
    LOGGED: 2021-03-26 10:12:42.947343
 THREAD_ID: 0
      PRIO: Error
ERROR_CODE: MY-000067
 SUBSYSTEM: Server
      DATA: unknown variable 'innodb_flush_log_at_trx_t=1'.
*************************** 2. row ***************************
    LOGGED: 2021-03-26 10:12:42.947766
 THREAD_ID: 0
      PRIO: Error
ERROR_CODE: MY-010119
 SUBSYSTEM: Server
      DATA: Aborting

The older events from error_log able are automatically purged when there is a need of space for new events.

The error_log table status can be monitored from SHOW STATUS variables.

mysql> show global status like '%error_log%';
+---------------------------+------------------+
| Variable_name             | Value            |
+---------------------------+------------------+
| Error_log_buffered_bytes  | 8368             |
| Error_log_buffered_events | 62               |
| Error_log_expired_events  | 0                |
| Error_log_latest_write    | 1616753905924032 |
+---------------------------+------------------+
4 rows in set (0.00 sec

Limitations of error_log table

  • TRUNCATE TABLE is not permitted on error_log table.
  • The table cannot be index , each column is already indexed by default.

Finally ,introduction of error_log table in MySQL 8 has made error readability more convenient and easy, now the error log can be accessed from remote clients as well with few simple SQL queries without accessing the physical system file.

MySQL error logs table feature benefits the remote connections using MySQL shell and will benefits a lot in DBaaS like AWS RDS , AZURE MySQL , Google Cloud SQL platforms. Where the error log needs a console and log retention is complex.

Published by Waseem Akram

Waseem Akram is an Oracle and AWS certified MySQL DBA. Working in MyDBOPS IT Solutions on MySQL and related technologies to ensures database performance. Handling multi client tasks round the clock and also working with a team of experts at MyDBOPS.
View all posts by Waseem Akram

Published
March 28, 2021March 30, 2021

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

  • Что такое логи
  • Как читать логи
  • Логи доступа (access_log)
  • Логи ошибок (error_log)
  • FTP-логи
  • Логи операций в панели управления
  • Как анализировать логи при высокой нагрузке на сервер

Что такое логи

Логи — это файлы текстового формата, в которых хранятся следующие данные:

  • информация о пользователях,
  • информация о действиях на сервере,
  • информация о дате и времени операций,
  • системная информация о работе сервера.

На хостинге SpaceWeb хранятся логи за прошедший месяц (30 дней): они создаются автоматически в хронологическом порядке. Один файл лога включает в себя историю операций за один прошедший день.

Как читать логи

Каждый log-файл имеет собственную структуру: она отличается в зависимости от типа логов. Чаще всего используются:

  • логи доступа или access_log,
  • логи ошибок или error_log,
  • FTP-логи,
  • логи операций в панели управления.

Анализ логов проводится по-разному: это зависит от операции, которую нужно отследить. Например, если вы хотите поверить визиты на сайт и в панель управления, потребуются логи доступа и логи операций в панели управления. О типах логов и их назначении расскажем ниже.

Логи доступа (access_log)

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

Лог доступа имеет следующий вид:

test.ru 123.123.123.123 — — [01/Jan/2022:00:00:00 +0000] «GET /index.html HTTP/1.1» 200 198 «https://test.ru/» «Mozilla/5.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1)» 16143 0

Где:

  • test.ru — доменное имя сайта;
  • 123.123.123.123 — IP-адрес, с которого обращается клиент;
  • 01/Jan/2022:00:00:00 +0000 — дата и время запроса;
  • GET — метод запроса;
  • 200 — последний код ответа, если произошло внутреннее перенаправление (в примере — успешное обращение);
  • 198 — размер ответа в байтах без HTTP-заголовка. Если ответ был размера 0, в лог-файле он отобразится знаком -;
  • «https://test.ru/» «Mozilla/5.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1)» — информация о клиенте (браузере, с которого посетили сайт);
  • 16143 — PID процесса Apache;
  • 0 — время работы процесса Apache.

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

Логи ошибок (error_log)

error.log — это файл, в котором фиксируются все типы ошибок сервера. Логи ошибок  позволяют отследить, в какой момент возникла проблема: это поможет в ее решении.

Лог ошибок (error.log) имеет следующий вид: 

test.ru [Fri Jan 01 00:00:00 2022] [error] [client 123.123.123.123] File does not exist: /home/d/test/public_html/favicon.ico

Где:

  • test.ru — доменное имя сайта;
  • Fri Jan 01 00:00:00 2022 — дата и время возникновения ошибки;
  • 123.123.123.123 — IP-адрес, с которого обратился клиент.

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

FTP-логи

Логи FTP помогают отследить подключения по протоколу FTP и действия при удаленном соединении с сервером.

FTP-лог имеет следующий вид:

2022-01-01T00:00:00+03:00 vhXX pure-ftpd: (?@123.123.123.123) [DEBUG] Command [user] [vhXXtest]
2022-01-01T00:01:00+03:00 vhXX pure-ftpd: (?@123.123.123.123) [INFO] vhXXtest is now logged in
2022-01-01T00:02:00+03:00 vhXX pure-ftpd: (vhXXtest@123.123.123.123) [DEBUG] Command [retr] [configuration.php]
2022-01-01T00:03:00+03:00 vhXX pure-ftpd: (vhXXtest@123.123.123.123) [NOTICE] /home/v/vhXXtest/public_html//configuration.php downloaded (5317 bytes, 77503.32KB/sec)
2022-01-01T00:04:00+03:00 vhXX pure-ftpd: (vhXXtest@123.123.123.123) [DEBUG] Command [pasv] []
2022-01-01T00:05:00+03:00 vhXX pure-ftpd: (vhXXtest@123.123.123.123) [DEBUG] Command [stor] [configuration.php]
2022-01-01T00:06:00+03:00 vhXX pure-ftpd: (vhXXtest@123.123.123.123) [NOTICE] /home/v/vhXXtest/public_html//configuration.php uploaded (5165 bytes, 985.55KB/sec)
2022-01-01T00:07:00+03:00 vhXX pure-ftpd: (vhXXtest@123.123.123.123) [INFO] Logout.

Где:

  • 2022-01-01T00:00:00+03:00 — дата и время действия на сервере FTP,
  • 123.123.123.123 —  IP-адрес сервера,
  • vhXX — имя сервера,
  • vhXXtest — имя FTP-пользователя.

Логи FTP можно получить при обращении в службу технической поддержки.

Логи операций в панели управления

Логи операций позволяют отследить всю активность в панели управления SpaceWeb. Благодаря им вы сможете выявить несанкционированные посещения в системе.

Логи операций в панели управления имеют следующий вид:

46085314   Неуспешная авторизация в клиентской ПУ   123.123.123.123   2022-01-01 00:00:00
46172855   Сделан заказ на домен test.ru; mov;   test   2022-01-01 00:01:00
46172895   Удалён домен test.ru   test   2022-01-01 00:10:00
46518875   Выход из клиентской ПУ   123.123.123.123   test   2022-01-01 00:11:00
46554201   Создание папки   /testforum   test   2022-01-02 00:00:00
46554208   Создана база данных test_bd   test   2022-01-02 00:10:00
46554210   Установка CMS из панели управления   smf test.ru:/testforum/   test   2022-01-02 00:20:00

Где:

  • 46085314 — номер операции,
  • 123.123.123.123 — IP-адрес сервера,
  • test — имя пользователя панели управления,
  • 2022-01-01 00:00:00 — дата и время выполнения операции.

Логи операций в панели управления можно включить в разделе «Профиль» на вкладке Логи ПУ.

Как анализировать логи при высокой нагрузке на сервер

Для анализа логов подключитесь к серверу по SSH. Далее введите команду, которая подходит для вашего случая.

  • Проверьте, на какой странице было наибольшее число посещений за день:

cat test.ru/access_log | awk ‘{ print $8}’ | sort | uniq -c | sort -n -k 1 | tail -n 50

Вместо test.ru укажите корневую директорию сайта.

  • Чтобы проверить запросы за несколько прошедших дней, выполните команду:

cat test.ru/access_log*gz | awk ‘{ print $8}’ | sort | uniq -c | sort -n -k 1 | tail -n 50

Вместо test.ru укажите корневую директорию сайта. После этого сформируется архив с журналом логов.

  • Выявить аномальное число запросов с одного IP-адреса за день:

cat test.ru/access_log | awk ‘{ print $2}’ | sort | uniq -c | sort -n -k 1 | tail -n 50

Вместо test.ru укажите корневую директорию сайта.

  • Чтобы проверить запросы за несколько прошедших дней, выполните команду:

cat test.ru/access_log*gz | awk ‘{ print $2}’ | sort | uniq -c | sort -n -k 1 | tail -n 50

Вместо test.ru укажите корневую директорию сайта. После этого сформируется архив с журналом логов.

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.

Because of handling your users’ requests, Apache serves as the front application. It is crucial to understand what your server is doing, what file users are accessing, from where they came, and much, much more.

The visibility that Apache logs give you is invaluable in understanding the traffic coming to your application, the errors that happen, and the performance of the user-facing elements. Today, we will look into what the Apache web server logs are, how to interpret them, and how to analyze them easily.

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

The Apache Common Log Format is one of the two most common log formats used by HTTP servers. You can expect it to see its definition to look similar to the following line:

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

As you can see the following elements are present:

  • %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

The Apache Combined Log Format is another format often used with access logs. It’s very similar to the Common Log Format but includes two additional headers – the referrer and the user agent. Its definition looks as follows:

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

It is possible to have multiple Apache access logs at the same time without any additional effort. We may want a limited set of information available in some files for quick scanning and the full log using the Combined Log Format if we need the complete information. For example, we could have three access log files – one that includes time, user agent, and the status code, the second that includes the time, IP address, and referrer used, and the third – the Common Log Format.

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

There are cases when you would like to write logs only when a certain condition is met. This is what Apache Server calls conditional logging. It is done by using the CustomLog directive and environment variables. For example, if you would like to log all requests accessing your PNG files in a separate file you can do that the following way:

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.

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:

ErrorLogFormat “[%{u}t] [%-m:%l] [pid %P:tid %T] [client %a] %M”

The above configuration would produce an Apache error log entry similar to the following one:

[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

In the above example the following formatting options were used:

  • %{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

In addition to what we discussed so far there is one other thing worth mentioning – the level of log events. The LogLevel directive allows specifying the level of log messages on a per-module basis. For example, if we would like the main log level for all events to be set to the info level but have the error level only for the rewrite module, we could have a configuration directive as follows:

LogLevel info rewrite:error

The following logging levels are described in Apache server documentation:

  • 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

Sematext Logs is part of the Sematext Cloud full-stack monitoring solution providing you with all you need when it comes to observability. With Sematext Cloud, you get an overview of your Apache servers, errors report, HTTP report, including top HTTP methods and paths with an average response size visualization and requests table. You can see your users with the top User Agents used to access resources served by your Apache servers and, finally, the sources for the data. All within a single Apache Logs monitoring in Sematext Cloud.

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

Conclusion

Analyzing your Apache servers logs is invaluable in understanding the traffic coming to your application, the errors that happen, and the performance of the user-facing elements. A log management tool such as Sematext Logs does this job for you.

More than understanding server logs, knowing what resources were accessed, who accessed them, and how long it took to process the request is crucial to understanding your user’s behavior. You also need to be sure that you are aware of every error that happens so that you can react as soon as possible. Combining that with the need for distributed infrastructures to handle a large number of concurrent users and provide high availability, using an observability tool is a necessity.

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.

Понравилась статья? Поделить с друзьями:
  • Error log ispmanager
  • Error code 2fd7b735 nba 2k20
  • Error log information saved in errorlog txt last chaos как решить
  • Error code 0411 dell
  • Error log handler