Ubuntu файл логов. Отслеживание логов Linux в реальном времени

A Linux Administrator should be able to read and understand the various types of messages that are generated by all Linux systems in order to troubleshoot an issue. These messages, called logs, are initiated by Linux and the applications running on it. Linux continuously creates, stores and recycles these logs through various configuration files, programs, commands, and daemons. If you know how to read these files and make optimal use of the various commands we will mention in this tutorial, you can troubleshoot your issues like a pro!

It is important to note that Linux keeps its log files in the /var/log directory in text format.

Viewing System Logs on Ubuntu

In order to reach the core of an issue, or to see if your application or system is behaving in the desired manner, you can view the system log files either graphically or through command line in the following ways:

  • Gnome Logs utility (Graphic)
  • Log File Viewer utility (Graphic)
  • Linux Terminal (Command Line)

View Log Files Through Gnome Logs

‘Logs’ is the default utility that comes with the latest versions of Ubuntu e.g., Ubuntu 18.04 LTS (Bionic Beaver). In order to access it,

Type Logs in the Ubuntu dash:

You will be able to see the Logs utility open, with the option to view logs for Applications, System, Security and Hardware.

Click on the System tab to view system logs:

Here you can view all the system logs along with the time they were generated. You can perform the following actions through this window:

  • Display the contents of a log by clicking on it.
  • Search for a log by clicking the search icon and then providing keywords in the search bar. The search bar also offers a number of filters that you can apply in order to exactly specify What (Select a Journal field to filter the logs according to it) and When (Select the timestamp range of the log entries to be shown) you want to see:

  • You can also export logs to a file by clicking the export button located at the top right corner of the Logs window. You can then save the log file by specifying a name and location.

Through Log File Viewer

The Log File Viewer is the default utility that comes with the older versions of Ubuntu. If your edition of Ubuntu does not have this application by default, you can download and install it through Ubuntu Software.

In order to access the Log File Viewer:

  • Enter Log Viewe r in Ubuntu Dash
  • If you have installed this program through Ubuntu Software, you can launch it by searching for it in the Ubuntu Software as follows and then clicking the Launch button:

The Log File Viewer will appear as follows:


The left panel of the window shows a number of default log categories and the right panel shows a list of logs for the selected category.

Click on the syslog tab to view system logs. You can search for a specific log by using ctrl+F control and then enter the keyword. When a new log event is generated, it is automatically added to the list of logs and you can see it in bolded form. You can also filter your logs through the Filters menu located in the top menu bar.

In order to view a log for a specific application, click the Open option from the File menu. The following Open Log window will open for you to choose the log from:

Click on a log file and click Open . You will now be able to see logs from the selected log file in the Log File Viewer.

View Log Files Through the Terminal

You can also view system logs through the command line, i.e., the Ubuntu Terminal.

Open the Terminal and enter the following command:

This command fetches all the messages from the kernel’s buffer. You can see the output as follows:

You will see that this is a lot of information. This information will only be useful if we apply some filters to view what we want to see.

Customizing dmesg output

  • In order to see messages at your own pace, use the following command:

$ dmesg |less

This command will display only a specific number of messages per screen. You can press Enter in order to move to the next message or press Q to exit the command.

  • In order to search for a message that contains a specific keyword, use the following command:
$ dmesg |grep

For example, if you want to search for all the messages containing the word core, you can use the following command:

$ dmesg |grep core

The Terminal will now display only those messages containing the word “core” in red color.

Open a Log File with cat Command

The dmesg command opens all the logs from the /var/log directory. In order to open the log file from some other location, use the following command:

$ cat

$ cat /var/log/syslog

This command will print logs from the syslog file to the screen. You will again observe that this command prints all the information and it is not easy to skim through. Here again, you can use the ‘grep’ and ‘less’ filters to display the desired output as follows:

$ cat |grep

$ cat |less

Writing To the System Log

Sometimes we need to write custom messages to our system log during the troubleshooting process. Both the Gnome Log and the Log File Viewer programs are built to display a customized message that you can write through the Terminal.

Open the Ubuntu Terminal and type the following command:

$ logger “This is a custom message”


You can see the custom log message, at the end of the above log list, displayed in the graphical log file viewer.

You can also use the logger command within a script for providing additional information. In that case, please use the following command within your script:

$ logger -t scriptname “This is a custom message”

By practicing along with this tutorial, you can learn to troubleshoot your system and application issues by accessing and understanding system logs.

How to View System Log Files on Ubuntu 18.04 LTS

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

Все лог файлы linux распологаются в папке:
/var/log

log-файлы линукс:
messages Содержит глобальные системные логи Linux, в том числе те, которые регистрируются при запуске системы.
dmesg Содержит сообщения, полученные от ядра. Регистрирует много сообщений еще на этапе загрузки, в них отображается информация об аппаратных устройствах, которые инициализируются в процессе загрузки. Количество сообщений в логе ограничено, и когда файл будет переполнен, с каждым новым сообщением старые будут перезаписаны.
auth.log Содержит информацию об авторизации пользователей в системе, включая пользовательские логины и механизмы аутентификации, которые были использованы.
boot.log Содержит информацию, которая регистрируется при загрузке системы.
daemon.log Включает сообщения от различных фоновых демонов
kern.log Тоже содержит сообщения от ядра, полезны при устранении ошибок пользовательских модулей, встроенных в ядро.
lastlog Отображает информацию о последней сессии всех пользователей. Это нетекстовый файл, для его просмотра необходимо использовать команду lastlog.
mail.log журналы сервера электронной почты, запущенного в системе.
user.log Информация из всех журналов на уровне пользователей.
Xorg.x.log Лог сообщений Х сервера.
btmp Содержит информацию о неудачных попытках входа.
cups Все сообщения, связанные с печатью и принтерами.
cron Всякий раз когда демон Cron запускает выполнения программы, он записывает отчет и сообщения самой программы в этом файле.
secure Содержит информацию, относящуюся к аутентификации и авторизации.
wtmp Содержит журнал входа пользователей в систему. Используйте команду wtmp, чтобы отобразить содержимое этого файла.
faillog Содержит неудачные попытки входа в систему. Используйте команду faillog, чтобы отобразить содержимое этого файла.
mysqld.log Содержит файлы логов сервера баз данных MySQL.

Посмотреть логи linux можно с помощью нескольких консольных программ. Ниже разберем несколько примеров:

1. Вывод и пролистываение текста с помощью less:
less /var/log/messages

2. Просмотр логов в реальном времени:
tail -f /var/log/messages

3. Открываем файл с помощью cat:
cat /var/log/dmesg

4. Выводим первые 10 строк из файла:
head /var/log/dmesg

5. Выводим последние 10 строк из файла:
tail /var/log/dmesg

6. Выводим определенное количество строк:
head -n3 /var/log/dmesg
где, -n3 — количество строк которое нужно показать.

7. Выводим только ошибки:
grep -i error /var/log/messages

Кроме консоли и текстовых редакторов вы также можете использовать графическую программу «System Log Viewer», которая в удобной и наглядной форме покажет вам логи в линукс .

Если вы взялись за администрирование Linux, будьте готовы к тому, что просмотр и анализ лог-файлов будет отнимать львиную долю времени того времени, что вы проводите в консоли. Анализ лога основной (а чаще всего и единственный) способ разобраться в поведении сервера.

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

Просмотр логов в Linux с помощью tail .

tail (переводится как хвост) позволяет просмотреть 10 последних строк файла. Если нужно больше, достаточно об этом сказать. Например, 25:

# tail -n 25 /var/log/httpd/error_log

[ hc @ host ~ ] # tail -n 25 /var/log/httpd/error_log

А можно просто:

# tail -25 /var/log/httpd/error_log

[ hc @ host ~ ] # tail -25 /var/log/httpd/error_log

Второй полезный параметр, который можно передать -f . C этим параметром tail выводит заданное количество последних строк и продолжает считывать добавляемые строки, до тех пор пока вы не нажмете Сtrl+C – т.е. вы можете в живую отслеживать изменения в лог-файле:

# tail -5f /home/sites/web/site.ru/logs/site.ru.log 178.45.0.0 - - "GET / HTTP/1.0" 200 17401 "http://site.ru/allsorts/" "Mozilla/5.0 (iPad; CPU OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A405 Safari/600.1.4" 217.118.0.0 - - "GET /allsorts HTTP/1.0" 301 - "http://site.ru/" 217.118.0.0 - - "GET /allsorts/ HTTP/1.0" 200 16663 "http://site.ru/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1" 85.95.0.0 - - "GET / HTTP/1.0" 200 17401 "http://vk.com/away.php" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 OPR/34.0.2036.50" 85.95.0.0 - - "GET /allsorts/ HTTP/1.0" 200 16663 "http://site.ru/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 OPR/34.0.2036.50"

[ hc @ host ~ ] # tail -5f /home/sites/web/site.ru/logs/site.ru.log

178.45.0.0 - - [ 23 / Jan / 2016 : 19 : 45 : 02 + 0300 ] "GET / HTTP/1.0" 200 17401 "http://site.ru/allsorts/" "Mozilla/5.0 (iPad; CPU OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A405 Safari/600.1.4"

217.118.0.0 - - [ 23 / Jan / 2016 : 19 : 46 : 34 + 0300 ] "GET /allsorts HTTP/1.0" 301 - "http://site.ru/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1"

217.118.0.0 - - [ 23 / Jan / 2016 : 19 : 46 : 35 + 0300 ] "GET /allsorts/ HTTP/1.0" 200 16663 "http://site.ru/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1"

85.95.0.0 - - [ 23 / Jan / 2016 : 19 : 47 : 34 + 0300 ] "GET /allsorts/ HTTP/1.0" 200 16663 "http://site.ru/" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36 OPR/34.0.2036.50"

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

# tail -f -n 5 -s 3 /home/sites/web/site.ru/logs/site.ru.log /var/log/httpd/domains/site.ru.error.log ==> /home/sites/web/site.ru/logs/site.ru.log /var/log/httpd/domains/site.ru.error.log

[ hc @ host ~ ] # tail -f -n 5 -s 3 /home/sites/web/site.ru/logs/site.ru.log /var/log/httpd/domains/site.ru.error.log

== > / home / sites / web / site . ru / logs / site . ru . log

37.113.0.0 - - [ 23 / Jan / 2016 : 19 : 55 : 45 + 0300 ] "GET /wp-content/themes/bigroll/img/delivery-feature-6.png HTTP/1.1" 200 18165 "http://site.ru/delivery/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1"

"GET /wp-content/themes/bigroll/img/delivery-truck.png HTTP/1.1" 200 15243 "http://site.ru/delivery/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1"

37.113.0.0 - - [ 23 / Jan / 2016 : 19 : 55 : 46 + 0300 ] "GET /wp-content/themes/bigroll/img/scooter-icon-small.png HTTP/1.1" 200 4322 "http://site.ru/delivery/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1"

37.113.0.0 - - [ 23 / Jan / 2016 : 19 : 55 : 46 + 0300 ] "GET /wp-content/themes/bigroll/img/link-button-shadow.png HTTP/1.1" 200 7792 "http://site.ru/delivery/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1"

37.113.0.0 - - [ 23 / Jan / 2016 : 19 : 55 : 46 + 0300 ] "GET /wp-content/themes/bigroll/img/header-bg.png HTTP/1.1" 200 194475 "http://site.ru/delivery/" "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1"

== > / var / log / httpd / domains / site . ru . error . log

[ Wed Jan 20 04 : 38 : 36 2016 ] [ error ] [ client 46.166.0.0 ] client denied by server configuration : / home / sites / web / site . ru / public_html / xmlrpc . php

[ Wed Jan 20 13 : 15 : 43 2016 ] [ error ] [ client 69.84.0.0 ] client denied by server configuration : / home / sites / web / site . ru / public_html / xmlrpc . php

[ Wed Jan 20 20 : 48 : 58 2016 ] [ error ] [ client 185.112.0.0 ] client denied by server configuration : / home / sites / web / site . ru / public_html / xmlrpc . php

[ Wed Jan 20 22 : 42 : 02 2016 ] [ error ] [ client 5.255.0.0 ] client denied by server configuration : / home / sites / web / site . ru / public_html / xmlrpc . php

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

Просмотр логов в Linux с помощью less .

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

Откроем файл:

# less /var/log/httpd/domains/big-roll.ru.error.log

[ hc @ host ~ ] # less /var/log/httpd/domains/big-roll.ru.error.log

Как видите мы можем спокойно листать содержимое файла с помощью стрелок курсора и клавиш PgUp и PgDn .
Запомните еще несколько полезных клавиш:
q – выход;
g – перейти в начало файла;
G – перейти в конец файла;
Ng – перейти на строку N (например, на 14 строку 14g);
N% – перейти на позицию N% (например, 35%);
F – перейти в режим отслеживания обновления файла, т.е. аналог tail -f ;
/pattern – прямой (вниз по файлу) поиск по образцу pattern;
?pattern – обратный (вверх по файлу);
n – следующее совпадение образца поиска;
N – предыдущее совпадение;
Выход из режима отслеживания Ctrl+C ;
Полный список всех остальных клавиш и режимов вы можете поглядеть самостоятельно – нажав h – помощь (очень советую нажать).

Размещение перед именем файла символа канала (|) позволит использовать fifo (first in - first out, первый пришел - первый вышел) или именованный канал (named pipe) в качестве приемника для сообщений. Прежде чем запускать (или перезапускать) syslogd, необходимо создать fifo при помощи команды mkfifo. Иногда fifo используются для отладки.

Терминал и консоль

Терминал, такой как /dev/console.

Удаленная машина

Чтобы сообщения пересылались на другой хост, поместите перед именем хоста символ (@). Обратите внимание, что сообщения не пересылаются с принимающего хоста. (для работы данного назначения на клиенте и сервере в файле /etc/services должна быть прописана строчка syslog 514/udp , и открыт UTP-порт 514)

Список пользователей

Разделенный запятыми список пользователей, получающих сообщения (если пользователь зарегистрирован в системе). Сюда часто включается пользователь root.

Все зарегистрированные пользователи

Чтобы известить всех зарегистрированных пользователей при помощи команды wall, используйте символ звездочки (*).

Пример несложного syslog.conf:

# Все сообщения ядра выдавать на консоль. #kern.* /dev/console # Все логи уровня info или выше, кроме сообщений электронной почты, а так же # не логировать сообщения аутентификации и сообщений демона cron! *.info;mail.none;authpriv.none;cron.none /var/log/messages # Записывать в отдельный файл сообщения, содержащие конфиденциальную # информацию аутентификации, независимо от их уровня. authpriv.* /var/log/secure # Все сообщения почтовой системы тоже записывать в отдельный файл. mail.* -/var/log/maillog # Логировать сообщения планировщика в файл /var/log/cron cron.* /var/log/cron # Сообщения о чрезвычайных ситуациях должны немедленно получить # все пользователи системы *.emerg * # Сохранять сообщения новостей уровня crit и выше в отдельный файл. uucp,news.crit /var/log/spooler # Сохранять сообщения загрузки в boot.log local7.* /var/log/boot.log

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

  • строки, начинающиеся с #, и пустые строки игнорируются.
  • Символ * может использоваться для указания всех категорий или всех приоритетов.
  • Специальное ключевое слово none указывает, что журналирование для этой категории не должно быть выполнено для этого действия.
  • Дефис перед именем файла (как -/var/log/maillog в этом примере) указывает, что после каждой записи журнал не должен синхронизироваться. В случае аварии системы вы можете потерять информацию, но отключение синхронизации позволит повысить производительность.

В синтаксисе конфигурационного файла можно поставить перед приоритетом знак! , чтобы показать, что действие не должно применяться, начиная с этого уровня и выше . Подобным образом, перед приоритетом можно поставить знак = , чтобы показать, что правило применяется только к этому уровню, или != , чтобы показать, что правило применяется ко всем уровням, кроме этого. Ниже показано несколько примеров (man syslog.conf можно найти множество других примеров):

# Посылать все сообщения ядра в /var/log/kernel. # Посылать все сообщения уровня critical и higher на удаленную машину sysloger и на консоль # Посыласть все сообщения уровня info, notice и warning в /var/log/kernel-info # kern.* /var/log/kernel kern.crit @sysloger kern.crit /dev/console kern.info;kern.!err /var/log/kernel-info # Посылать все сообщения почтовой системы, кроме уровня info в /var/log/mail. mail.*;mail.!=info /var/log/mail

Я постарался максимально понятно работу syslogd показать на схеме:

Запуск демона syslogd

Запуск демона протоколирования запускаются на этапе инициализации системы посредством скрипта /etc/rc.d/init.d/syslog , однако для того, чтобы задать параметры запуска, нет необходимости корректировать этот скрипт - начиная с версии 7.2, опции запуска считываются из отдельного конфигурационного файла /etc/sysconfig/syslog (/etc/default/syslog в debian) .

Вот некоторые возможные параметры запуска демона syslogd:

  • -a /folder/socket - указание дополнительного слушающего сокета (не забудьте предварительно создать сокет)
  • -d - отладочный режим. При этом демон не переходит в фоновый режим и выдает все сообщения на текущий терминал;
  • -f имя-конфигурационного-файла . Задает имя альтернативного конфигурационного файла, который будет использоваться вместо заданного по умолчанию /etc/syslog.conf;
  • -l список-хостов - задание списка хостов, имена которых не должны записываться с указанием полного доменного имени (FQDN - Full Qwalified Domain Name);
  • -m минут - запущенный без этой опции sysklogd через каждые 20 минут записывает в протокол сообщения категории mark (временные отметки). С помощью опции -m можно либо изменить интервал между отметками, либо вовсе отменить выдачу таких сообщений;
  • -p socket - задание альтернативного сокета UNIX (вместо прослушиваемого по умолчанию /dev/log);
  • -r - разрешение принимать сообщения от удаленных хостов;
  • -x - запрет определения имени хоста по его адресу для предотвращения зависания при работе на одном хосте с сервером DNS.
  • -v - показать версию и закончить работу

После запуска демона syslogd создается файл статуса /var/lock/subsys/syslog нулевой длины, и файл с идентификационным номером процесса /var/run/syslogd.pid .

С помощью команды
kill -SIGNAL `cat /var/run/syslogd.pid`

можно послать демону syslogd один из следующих сигналов: SIGHUP - перезапуск демона; SIGTERM - завершение работы; SIGUSR1 - включить/выключить режим отладки.

Вообще-то в системе запускаются два демона протоколирования - syslogd и klogd . Оба демона входят в состав пакета sysklogd .

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

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

Автоматическая ротация (обновление заполненных файлов) и архивирование журналов

Со временем, файл журнала имеет свойство увеличиваться, особенно при интенсивной работе какого-либо сервиса. Соответственно, необходимо иметь возможность контролировать размер журналов. Это делается при помощи команды logrotate , которая обычно выполняется демоном cron . О работе cron я расскажу в следующих статьях. Главная цель команды logrotate состоит в том, чтобы периодически создавать резервные копии журналов и создавать новые чистые журналы. Сохраняется несколько поколений журналов и, когда завершается срок жизни журнала последнего поколения, он может быть заархивирован (сжат). Результат может быть отправлен по почте, например, ответственному за ведение архивов.

Для определения порядка ротации и архивирования журналов используется конфигурационный файл /etc/logrotate.conf . Для разных журналов можно задать разную периодичность, например, ежедневно, еженедельно или ежемесячно, кроме того, можно регулировать количество накапливаемых поколений, а также указать, будут ли копии архивов отправляться ответственному за ведение архивов и, если будут, когда. Ниже показан пример файла /etc/logrotate.conf:

# сначала заданы параметры "по-умолчанию" (глобальные опции) # обновлять файлы журнала еженедельно weekly # хранить архив логов за 4 последние недели rotate 4 # создавать новый (пустой) файл после ротации (обновления) create # раскомментируйте, если желаете, чтобы сохраненные файлы сжимались #compress # включить настройки ротации из указанного каталога include /etc/logrotate.d # не хранить wtmp, или btmp -- настройки ротации данных журналов следующие: /var/log/wtmp { missingok monthly create 0664 root utmp rotate 1 } /var/log/btmp { missingok monthly create 0664 root utmp rotate 1 } # специфичные системные журналы могут быть настроены ниже

Глобальные опции размещаются в начале файла logrotate.conf . Они используются по умолчанию, если где-то в другом месте не задано ничего более определенного. В примере ротация журналов происходит еженедельно и резервные копии сохраняются в течение четырех недель. Как только производится ротация журнала, на месте старого журнала автоматически создается новый. Файл logrotate.conf может содержать спецификации из других файлов. Так, в него включаются все файлы из каталога /etc/logrotate.d.

В этом примере также содержатся специальные правила для /var/log/wtmp и /var/log/btmp (хранящие информацию о удачных и неудачных попытках входя в систему), ротация которых происходит ежемесячно. Если файлы отсутствуют, сообщение об ошибке не выдается. Создается новый файл и сохраняется только одна резервная копия.

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

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

/var/log/messages { rotate 5 mail [email protected] size 100k postrotate /usr/bin/killall -HUP syslogd endscript }

В этом примере ротация /var/log/messages производится по достижении им размера 100 КБ. Накапливается пять резервных копий, и когда истекает срок жизни самой старой резервной копии, она отсылается по почте на адрес [email protected] Командное слово postrotate включает скрипт, перезапускающий демон syslogd после завершения ротации путем отправки сигнала HUP. Командное слово endscript необходимо для завершения скрипта, а также в случае, если имеется скрипт prerotate. Более полную информацию см. в страницах руководства man для logrotate.

Параметры , задаваемые в конфигурационном файле logrotate.conf:

  • compress | nocompress (старые версии сжимаются или не сжимаются с помощью gzip)
  • compresscmd (задает программу сжатия, по умолчанию - gzip)
  • uncompresscmd (задает программу разжатия, по умолчанию - ungzip)
  • compressext (задает суффикс для сжатых файлов)
  • compressoptions (задает параметры программы сжатия; по умолчанию - "-9", т.е. максимальное сжатие для gzip)
  • copytruncate | nocopytruncate (обычно старая версия переименовывается и создается новая версия журнала; при задании этого параметра logrotate копирует журнал в новый файл, а затем обрезает старый; используется, если программа, создающая журнал, не умеет его закрывать; теряются записи, сделанные в промежутке между копированием и обрезанием; а поможет ли, если создающая журнал программа вместо режима append просто пишет в файл, используя внутренний указатель?)
  • create [права-доступа владелец группа] | nocreate (сразу после переименования старой версии журнала и до вызова postrotate создается новый журнал с указанными атрибутами - права доступа задаются в восьмеричном виде, как в chmod.2; если атрибуты не указаны, то берутся от старого журнала)
  • daily (смена версий в серии происходит ежедневно)
  • delaycompress | nodelaycompress (некоторые программы не сразу закрывают журнал, в этом случае сжатие надо отложить до следующего цикла)
  • errors email (кому направлять сообщения об ошибках)
  • extension суффикс (задается суффикс, добавляемый к именам файлов при ротации перед суффиксом сжатия)
  • ifempty | notifempty (смена версий даже если файл пуст; действует по умолчанию)
  • include имя-файла | имя-директории (текстуально подставить файл или все файлы из указанной директории; не включаются поддиректории, специальные файлы и файлы с суффиксами из списка исключений; нельзя использовать внутри секции)
  • mail адрес | nomail (когда смена версий приводит к необходимости удалить старый журнал, то послать его по указанному адресу)
  • mailfirst (посылать не удаляемую версию журнала, а первую)
  • maillast (посылать удаляемую версию журнала; действует по умолчанию)
  • missingok | nomissingok (не посылать сообщения об ошибке, если журнал отсутствует)
  • monthly (смена версий происходит ежемесячно)
  • olddir директория | noolddir (во время смены версий журнал перемещается в указанную директорию; д.б. на том же физическом устройстве)
  • postrotate (все дальнейшие строчки до строки endscript исполняются как команды shell после процесса смены версии)
  • prerotate (все дальнейшие строчки до строки endscript исполняются перед процессом смены версии)
  • rotate число (сколько старых версий хранить; если 0, то ни одной)
  • size байт (смена версии происходит, если размер журнала превысил указанное число; можно использовать суффиксы "k" - килобайт - и "M" - мегабайт)
  • sharedscripts | nosharedscripts (выполнять команды prerotate и postrotate только один раз для всех файлов, описанных в секции)
  • tabooext [+] список-суффиксов (задание списка суффиксов-исключений для include; если указан знак "плюс", то дополнение, иначе замена; по умолчанию: .rpmorig, .rpmsave, .rpmnew, ",v", .swp и "~")
  • weekly (смена версий происходит еженедельно)

Изучение и мониторинг журналов

Записи в журналах обычно содержат метку времени, имя хоста, на котором выполняется описываемый процесс, и имя процесса. Просматривать журналы можно при помощи программы постраничного вывода, например, less , искать определенные записи (например, сообщения ядра от определенного демона) можно при помощи команды grep :

# less /var/log/messages # grep "ppp" /var/log/messages | tail Dec 17 16:34:25 proxy pppd: Connection terminated. Dec 17 16:34:25 proxy pppd: Exit. Dec 17 16:35:57 proxy pppd: LCP terminated by peer (^P]kV^@

Компьютер может работать не постоянно и выключаться, допустим на ночь. Поэтому в /var/log/messages записи хранятся циклически от запуска компьютера к выключению, это можно заметить по сообщениям:

Дек 17 08:32:56 syslog-server syslogd 1.4-0: restart. Дек 17 08:32:56 syslog-server syslog: запуск syslogd succeeded Дек 17 08:32:56 syslog-server kernel: klogd 1.4-0, log source = /proc/kmsg started. Дек 17 08:32:56 syslog-server syslog: запуск klogd succeeded

Dec 17 08:32:56 syslog-server kernel: Kernel command line: auto BOOT_IMAGE=linux ro root=303 BOOT_FILE=/boot/vmlinuz-2.4.2-2 Dec 17 08:32:56 syslog-server kernel: Memory: 125652k/130560k available (1365k kernel code, 4200k reserved, 92k data, 236k init, 0k highmem) Dec 17 08:32:56 syslog-server kernel: CPU: Intel(R) Pentium(R) 4 CPU 1.60GHz stepping 02

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

Иногда может возникать необходимость мониторинга системных журналов с целью поиска текущих событий. Например, можно попробовать поймать редко случающееся событие в тот момент, когда оно произошло. В таком случае можно использовать команду tail с опцией -f для отслеживания содержимого системного журнала. Пример:

# tail -f /var/log/messages | grep syslog-server Dec 17 16:46:09 syslog-server pppd: pptpd-logwtmp.so ip-up ppp0 maikop 94.77.0.150 Dec 17 16:46:09 syslog-server pppd: Script /etc/ppp/ip-up finished (pid 12552), status = 0x0 Dec 17 16:46:49 syslog-server pptpd: CTRL: Client 85.175.197.65 control connection started Dec 17 16:46:49 syslog-server pptpd: CTRL: Starting call (launching pppd, opening GRE) Dec 17 16:46:49 syslog-server pppd: Plugin /usr/lib/pptpd/pptpd-logwtmp.so loaded.

Кроме файлов-журналов, указанных в /etc/syslog.conf, существуют так же и другие файлы, например файл , который хранит информацию о процессе загрузки системы до запуска syslogd, а так же файлы , имеющие двоичный формат и и хранящие информацию о последнем входе пользователя в систему, о всех удачных входах пользователей в систему и о всех неудачных входах пользователей в систему соответственно. Так же в каталоге /var/log/ могут находится лог-файлы таких демонов как веб-сервер или прокси-сервер. Формат данных файлов аналогичен журналам syslogd.

На последок, хотелось бы сделать акцент на том, что данный протокол очень не защищен, т.к. syslog не содержит никаких средств защиты от подделок сообщений. Хуже того, использование протокола UDP позволяет злоумышленникам посылать сообщения от имени любого хоста. Ваша локальная сеть должна быть защищена экраном от приема пакетов с поддельными локальными адресами (хотя это не помешает посылать поддельные сообщения изнутри локальной сети) и от приема пакетов снаружи на порт 514/udp. Известны случаи переполнения диска ложными сообщениями.

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

Конфиденциальность сообщений не обеспечивается, так как они передаются открытым текстом.

Если при настройке генератора сообщений указать неправильный адрес коллектора или релея, то никаких сообщений об ошибке не будет - сообщения будут удаляться (или записываться в чужой журнал).

Были предложены несколько проектов улучшения протокола syslog. Например, документ RFC 3195 предлагает систему протоколирования (syslog-conn), основанную на TCP, обеспечивающую гарантированную доставку сообщений в правильной последовательности. Проект syslog-sign предлагает обеспечить аутентификацию, упорядоченность, целостность сообщений и обнаружение пропавших сообщений за счет генерации специальных сообщений, содержащих цифровую подпись (signature) блока предыдущих сообщений с сохранением стандартного протокола и формата syslog и использованием UDP.

Подведем небольшой итог:

В линукс есть единый демон, отвечающий за журналирование событий локальной системы и удаленных систем. Все события собираются из сокета /dev/log, порта UDP - 514, а так же от "помощника" - демона klogd, который присылает сообщения от ядра. Все собранные сообщения фильтруются демоном syslogd через правила в файле /etc/syslog.conf и в соответствии с правилами распределяются по соответствующим местам назначения. Файлы логов периодически "обрезаются". Периодичность определяет файл logrotate.conf и команда logrotate, которая запускается системным планировщиком - cron.

На сегодня это все. Надеюсь описал все максимально понятно. Со временем буду дополнять статью!

С Уважением, Mc.Sim!

Introduction

One of the things which makes GNU/Linux a great operating system is that virtually anything and everything happening on and to the system may be logged in some manner. This information is invaluable for using the system in an informed manner, and should be one of the first resources you use to trouble-shoot system and application issues. The logs can tell you almost anything you need to know, as long as you have an idea where to look first.

Your Ubuntu system provides vital information using various system log files. These log files are typically plain ASCII text in a standard log file format, and most of them sit in the traditional system log subdirectory /var/log . Many are generated by the system log daemon, syslogd on behalf of the system and certain applications, while some applications generate their own logs by writing directly to files in /var/log .

This guide talks about how to read and use several of these system log files, how to use and configure the system logging daemon, syslogd , and how log rotation works. See the Resources section for additional information.

Target Audience

This guide will be simple enough to use if you have any experience using the console and editing text files using a text editor. See the end of this document for some essential commands that may help you find your way around these files if you"re relatively new to the command line.

System Logs

System logs deal primarily with the functioning of the Ubuntu system, not necessarily with additional applications added by users. Examples include authorization mechanisms, system daemons, system messages, and the all-encompassing system log itself, syslog .

Authorization Log

The Authorization Log tracks usage of authorization systems, the mechanisms for authorizing users which prompt for user passwords, such as the Pluggable Authentication Module (PAM) system, the sudo command, remote logins to sshd and so on. The Authorization Log file may be accessed at /var/log/auth.log . This log is useful for learning about user logins and usage of the sudo command.

Use grep to cut down on the volume. For example, to see only information in the Authorization Log pertaining to sshd logins, use this:

grep sshd /var/log/auth.log | less

Daemon Log

A daemon is a program that runs in the background, generally without human intervention, performing some operation important to the proper running of your system. The daemon log at /var/log/daemon.log and contains information about running system and application daemons such as the Gnome Display Manager daemon gdm , the Bluetooth HCI daemon hcid , or the MySQL database daemon mysqld . This can help you trouble-shoot problems with a particular daemon.

Again, use grep to find specific information, plugging in the name of the daemon you"re interested in.

Debug Log

The debug log at /var/log/debug and provides detailed debug messages from the Ubuntu system and applications which log to syslogd at the DEBUG level.

Kernel Log

The kernel log at /var/log/kern.log provides a detailed log of messages from the Ubuntu Linux kernel. These messages may prove useful for trouble-shooting a new or custom-built kernel, for example.

Kernel Ring Buffer

The kernel ring buffer is not really a log file per se, but rather an area in the running kernel you can query for kernel bootup messages via the dmesg utility. To see the messages, use this:

dmesg | less

Or to search for lines that mention the Plug & Play system, for example, use grep like this:

dmesg | grep pnp | less

By default, the system initialization script /etc/init.d/bootmisc.sh sends all bootup messages to the file /var/log/dmesg as well. You can view and search this file the usual way.

System Log

The system log typically contains the greatest deal of information by default about your Ubuntu system. It is located at /var/log/syslog , and may contain information other logs do not. Consult the System Log when you can"t locate the desired log information in another log. It also contains everything that used to be in /var/log/messages .

Application Logs

Many applications also create logs in /var/log . If you list the contents of your /var/log subdirectory, you will see familiar names, such as /var/log/apache2 representing the logs for the Apache 2 web server, or /var/log/samba , which contains the logs for the Samba server. This section of the guide introduces some specific examples of application logs, and information contained within them.

Apache HTTP Server Logs

The default installation for Apache2 on Ubuntu creates a log subdirectory: /var/log/apache2 . Within this subdirectory are two log files with two distinct purposes:

    /var/log/apache2/access.log - records of every page served and every file loaded by the web server.

    /var/log/apache2/error.log - records of all error conditions reported by the HTTP server

By default, every time Apache accesses a file or page, the access logs record the IP address, time and date, browser identification string, HTTP result code and the text of the actual query, which will generally be a GET for a page view. Look at the Apache documentation for a complete rundown; quite a lot can be gleaned from this file, and indeed many statistical packages exist that perform analyses of these logs.

Also, every time any error occurs, Apache adds a line to the error log. If you run PHP with error and warning messages disabled, this can be your only way to identify bugs.

CUPS Print System Logs

The Common Unix Printing System (CUPS) uses the default log file /var/log/cups/error_log to store informational and error messages. If you need to solve a printing issue in Ubuntu, this log may be a good place to start.

Rootkit Hunter Log

The Rootkit Hunter utility (rkhunter) checks your Ubuntu system for backdoors, sniffers and rootkits, which are all signs of compromise of your system. The log rkhunter uses is located at /var/log/rkhunter.log .

Samba SMB Server Logs

The Server Message Block Protocol (SMB) server, Samba is popularly used for sharing files between your Ubuntu computer and other computers which support the SMB protocol. Samba keeps three distinct types of logs in the subdirectory /var/log/samba:

    log.nmbd - messages related to Samba"s NETBIOS over IP functionality (the network stuff)

    log.smbd - messages related to Samba"s SMB/CIFS functionality (the file and print sharing stuff)

    log. - messages related to requests for services from the IP address contained in the log file name, for example, log.192.168.1.1 .

X11 Server Log

The default X11 Windowing Server in use with Ubuntu is the Xorg X11 server, and assuming your computer has only one display defined, it stores log messages in the file /var/log/Xorg.0.log . This log is helpful for diagnosing issues with your X11 environment.

Non-Human-Readable Logs

Some log files found in the /var/log subdirectory are designed to be readable by applications, not necessarily by humans. Some examples of such log files which appear in /var/log follow.

Login Failures Log

The login failures log located at /var/log/faillog is actually designed to be parsed and displayed by the faillog command. For example, to print recent login failures, use this:

faillog

Last Logins Log

The last logins log at /var/log/lastlog should not typically be parsed and examined by humans, but rather should be used in conjunction with the lastlog command. For example to see a listing of logins with the lastlog command, displayed one page per screen with the less command, use the following command:

lastlog | less

Login Records Log

The file /var/log/wtmp contains login records, but unlike /var/log/lastlog above, /var/log/wtmp is not used to show a list of recent logins, but is instead used by other utilities such as the who command to present a listed of currently logged in users. This command will show the users currently logged in to your machine:

who

System Logging Daemon (syslogd)

The system logging daemon syslogd , also known as sysklogd , awaits logging messages from numerous sources and routes the messages to the appropriate file or network destination. Messages logged to syslogd usually contain common elements like system hostnames and time-stamps in addition to the specific log information.

Configuration of syslogd

The syslogd daemon"s configuration file is /etc/syslog.conf . Each entry in this file consists of two fields, the selector and the action. The selector field specifies a facility to be logged, such as for example the auth facility which deals with authorization, and a priority level to log such information at, such as info , or warning . The action field consists of a target for the log information, such as a standard log file (i.e. /var/log/syslog), or the hostname of a remote computer to send the log information to.

Echoing Messages to syslogd With Logger

A neat utility exists in the logger tool, which allows one to place messages into the System Log (i.e. /var/log/syslog) arbitrarily. For example, assume your user name is buddha , and you would like to enter a message into the syslog about a particularly delicious pizza you"re eating, you could use a command such as the following at a terminal prompt:

logger This Pizza from Vinnys Gourmet Rocks

and you would end up with a line in the /var/log/syslog file like this:

Jan 12 23:34:45 localhost buddha: This Pizza from Vinnys Gourmet Rocks

You can even specify a tag the messages come from, and redirect the output standard error too.

# # sample logger error jive # logmsg="/usr/bin/logger -s -t MyScript " # announce what this script is, even to the log $logmsg "Directory Checker FooScript Jive 1.0" # test for the existence of Fred"s home dir on this machine if [ -d /home/fred ]; then $logmsg "I. Fred"s Home Directory Found" else $logmsg "E. Fred"s Home Directory was NOT Found. Boo Hoo." exit 1 fi

Executing this script as chkdir.sh on the machine butters where Fred does not have a home directory, /home/fred , gives the following results:

[email protected]:~$./chkdir.sh MyScript: Directory Checker FooScript Jive 1.0 MyScript: E. Fred"s Home Directory was NOT Found. Boo Hoo. [email protected]:~$tail -n 2 /var/log/syslog Jan 12 23:23:11 localhost MyScript: Directory Checker FooScript Jive 1.0 Jan 12 23:23:11 localhost MyScript: E. Fred"s Home Directory was NOT Found. Boo Hoo.

So, as you can see, we received the messages both via standard error, at the terminal prompt, and they also appear in our syslog.

Log Rotation

When viewing directory listings in /var/log or any of its subdirectories, you may encounter log files with names such as daemon.log.0 , daemon.log.1.gz , and so on. What are these log files? They are "rotated" log files. That is, they have automatically been renamed after a predefined time-frame, and a new original log started. After even more time the log files are compressed with the gzip utility as in the case of the example daemon.log.1.gz . The purpose of log rotation is to archive and compress old logs so that they consume less disk space, but are still available for inspection as needed. What handles this functionality? Why, the logrotate command of course! Typically, logrotate is called from the system-wide cron script /etc/cron.daily/logrotate , and further defined by the configuration file /etc/logrotate.conf . Individual configuration files can be added into /etc/logrotate.d (where the apache2 and mysql configurations are stored for example).

This guide will not cover the myriad of ways logrotate may be configured to handle the automatic rotation of any log file on your Ubuntu system. For more detail, check the Resources section of this guide.

NOTE: You may also rotate system log files via the cron.daily script /etc/cron.daily/sysklogd instead of using logrotate. Actually, the utility savelog may produce unexpected results on log rotation which configuring logrotate seems to have no effect on. In those cases, you should check the cron.daily sysklogd script in /etc/cron.daily/sysklogd and read the savelog manual page to see if savelog is not in fact doing the rotation in a way that is not what you are specifying with logrotate .

Essential Commands

If you"re new to the console and the Linux command line, these commands will get you up and running to the point where you can work with log files at a basic level.

Getting Started

To change to the log directory, where most of these files sit, use the cd command. This saves having to type out a full path name for every subsequent command:

cd /var/log

Editing Files

You can view and edit files in GEdit or Kate, the simple text editors that come with Ubuntu and Kubuntu respectively, but these can be overkill when all you want to do is look at a file or make simple changes. The easiest editor to use from the console is nano, which is less powerful but also less complicated than vim or emacs. The command to edit a particular logfile /var/log/example.log using nano is:

nano example.log

Press Ctrl+X to exit. It will ask if you want to save your changes when you exit, but unless you run it with the sudo command the files won"t be writable. In general, you won"t want to save your changes to log files, of course.

Viewing Files

To simply look at a file, an editor is overkill. Use the less command, which pages through a file one screen at a time:

less example.log

You don"t need sudo to look at a file. Press h for help, or q to quit. The cursor keys and page up/down keys will work as expected, and the slash key ("/") will do a case-sensitive search; the n key repeats the last search.

Viewing the Beginning of Files

To see the first ten lines of a file, use the head command:

head example.log

To see some other number of lines from the beginning of the file, add the -n switch, thus:

head -n 20 example.log

Viewing the End of Files

To see the final ten lines of a file, the analogous command is tail:

tail example.log

Again, the -n switch gives you control over how many lines it displays:

tail -n 20 example.log

Watching a Changing File

Also, the -f ("follow") switch puts tail into a loop, constantly waiting for new additions to the file it"s displaying. This is useful for monitoring files that are being updated in real time:

tail -f example.log

Press Ctrl+C to quit the loop.

Searching Files

Because log files can be large and unwieldy, it helps to be able to focus. The grep command helps you strip out only the content you care about. To find all the lines in a file containing the word "system", for example, use this:

grep "system" example.log

To find all the lines containing "system" at the beginning of the line, use this:

grep "^system" example.log

Note the caret symbol, a regular expression that matches only the start of a line. This is less useful for standard log files, which always start with a date and time, but it can be handy otherwise. Not all files have a standard format.

Any time the result of a grep is still too long, you can pipe it through less:

grep "system" example.log | less

Resources

Additional information on system and application logs and syslogd is available via the following resources:

Local System Resources

System manual page for the dmesg kernel ring buffer utility

System manual page for the faillog command (and also the faillog configuration file via man 5 faillog)

System manual page for the grep pattern searching utility

System manual page for the head utility

System manual page for the kernel log daemon (klogd)

System manual for the last command which shows last logged in users

System manual page for the less paging utility

System manual page for the logger command-line interface to syslog utility

System manual page for the the logrotate utility

System manual page for the savelog log file saving utility

System manual page for the system log daemon (syslogd)

System manual page for the syslogd configuration file

System manual page for the tail utility