1. Overview
The Linux operating system, and many applications that run on it, do a lot of logging. These logs are invaluable for monitoring and troubleshooting your system.
What you’ll learn
- Viewing logs with a simple GUI tool
- Basic command-line commands for working with log files
What you’ll need
- Ubuntu Desktop or Server
- Very basic command-line knowledge (
cd
,ls
, etc.)
Originally authored by Ivan Fonseca.
How will you use this tutorial?
-
Only read through it
Read it and complete the exercises
What is your current level of experience?
-
Novice
Intermediate
Proficient
2. Log files locations
There are many different log files that all serve different purposes. When trying to find a log about something, you should start by identifying the most relevant file. Below is a list of common log file locations.
System logs
System logs deal with exactly that — the Ubuntu system — as opposed to extra applications added by the user. These logs may contain information about authorizations, system daemons and system messages.
Authorization log
Location: /var/log/auth.log
Keeps track of authorization systems, such as password prompts, the sudo
command and remote logins.
Daemon Log
Location: /var/log/daemon.log
Daemons are programs that run in the background, usually without user interaction. For example, display server, SSH sessions, printing services, bluetooth, and more.
Debug log
Location: /var/log/debug
Provides debugging information from the Ubuntu system and applications.
Kernel log
Location: /var/log/kern.log
Logs from the Linux kernel.
System log
Location: /var/log/syslog
Contains more information about your system. If you can’t find anything in the other logs, it’s probably here.
Application logs
Some applications also create logs in /var/log
. Below are some examples.
Apache logs
Location: /var/log/apache2/
(subdirectory)
Apache creates several log files in the /var/log/apache2/
subdirectory. The access.log
file records all requests made to the server to access files. error.log
records all errors thrown by the server.
X11 server logs
Location: /var/log/Xorg.0.log
The X11 server creates a seperate log file for each of your displays. Display numbers start at zero, so your first display (display 0) will log to Xorg.0.log
. The next display (display 1) would log to Xorg.1.log
, and so on.
Non-human-readable logs
Not all log files are designed to be read by humans. Some were made to be parsed by applications. Below are some of examples.
Login failures log
Location: /var/log/faillog
Contains info about login failures. You can view it with the faillog
command.
Last logins log
Location: /var/log/lastlog
Contains info about last logins. You can view it with the lastlog
command.
Login records log
Location: /var/log/wtmp
Contains login info used by other utilities to find out who’s logged in. To view currently logged in users, use the who
command.
This is not an exhaustive list!
You can search the web for more locations relevant to what you’re trying to debug. There is also a longer list here.
3. Viewing logs using GNOME System Log Viewer
The GNOME System Log Viewer provides a simple GUI for viewing and monitoring log files. If you’re running Ubuntu 17.10 or above, it will be called Logs. Otherwise, it will be under the name System Log.
System Log Viewer interface
The log viewer has a simple interface. The sidebar on the left shows a list of open log files, with the contents of the currently selected file displayed on the right.
The log viewer not only displays but also monitors log files for changes. The bold text (as seen in the screenshot above) indicates new lines that have been logged after opening the file. When a log that is not currently selected is updated, it’s name in the file list will turn bold (as shown by auth.log
in the screenshot above).
Clicking on the cog at the top right of the window will open a menu allowing you to change some display settings, as well as open and close log files.
There is also a magnifying glass icon to the right of the cog that allows you to search within the currently selected log file.
More information
If you wish to learn more about the GNOME System Log Viewer, you may visit the official documentation.
4. Viewing and monitoring logs from the command line
It is also important to know how to view logs in the command line. This is especially useful when you’re remotely connected to a server and don’t have a GUI.
The following commands will be useful when working with log files from the command line.
Viewing files
The most basic way to view files from the command line is using the cat
command. You simply pass in the filename, and it outputs the entire contents of the file: cat file.txt
.
This can be inconvenient when dealing with large files (which isn’t uncommon for logs!). We could use an editor, although that may be overkill just to view a file. This is where the less
command comes in. We pass it the filename (less file.txt
), and it will open the file in a simple interface. From here, we can use the arrow keys (or j/k if you’re familiar with Vim) to move through the file, use /
to search, and press q
to quit. There are a few more features, all of which are described by pressing h
to open the help.
Viewing the start or end of a file
We may also want to quickly view the first or last n
number of lines of a file. This is where the head
and tail
commands come in handy. These commands work much like cat
, although you can specify how many lines from the start/end of the file you want to view. To view the first 15 lines of a file, we run head -n 15 file.txt
, and to view the last 15, we run tail -n 15 file.txt
. Due to the nature of log files being appended to at the bottom, the tail
command will generally be more useful.
Monitoring files
To monitor a log file, you may pass the -f
flag to tail
. It will keep running, printing new additions to the file, until you stop it (Ctrl + C). For example: tail -f file.txt
.
Searching files
One way that we looked at to search files is to open the file in less
and press /
. A faster way to do this is to use the grep
command. We specify what we want to search for in double quotes, along with the filename, and grep
will print all the lines containing that search term in the file. For example, to search for lines containing “test” in file.txt
, you would run grep "test" file.txt
.
If the result of a grep
search is too long, you may pipe it to less
, allowing you to scroll and search through it: grep "test" file.txt | less
.
Editing files
The simplest way to edit files from the command line is to use nano
. nano
is a simple command line editor, which has all the most useful keybindings printed directly on screen. To run it, just give it a filename (nano file.txt
). To close or save a file, press Ctrl + X. The editor will ask you if you want to save your changes. Press y
for yes or n
for no. If you choose yes, it will ask you for the filename to save the file as. If you are editing an existing file, the filename will already be there. Simply leave it as it is and it will save to the proper file.
5. Conclusion
Congratulations, you now have enough knowledge of log file locations, usage of the GNOME System Log Viewer and basic command line commands to properly monitor and trouble-shoot problems that arise on your system.
Further reading
- The Ubuntu Wiki has an article that goes more in-depth into Ubuntu log files.
- This DigitalOcean Community article covers viewing Systemd logs
Was this tutorial useful?
Thank you for your feedback.
Приветствую читателей своего сайта. Сегодня я всесторонне рассмотрю тему тему логов в Ubuntu — ошибки, загрузка, системные логи, cron и остальное. Постараюсь дать обзорную информацию по основным моментам в этой теме. Материал в основном рассчитан на новичков, но возможно восполнит пробелы и специалистов.
Традиционно логи в Linux хранятся в директории /var/log. Вот описание стандартных лог файлов Ubuntu, которые там присутствуют. Кстати, если вы только планируете устанавливать ubuntu, то можете воспользоваться моей подробной статьей на этот счет — установка ubuntu server. Так же вам может быть интересен мой обзор и сравнение сервера убунту с другими linux системами — Ubuntu Server — обзор для начинающих, сравнение, отзывы.
- syslog или messages. Последнего чаще всего нет и вместо него только syslog. Это традиционные глобальные системные журналы операционной системы linux. Сюда пишутся события загрузки, ядра системы, системы инициализации systemd и т.д.
- auth.log — лог авторизации и аутентификации в системе.
- dmesg — в этом логе хранится информация о загрузке ядра и драйверов оборудования.
- alternatives.log — лог файл программы update-alternatives. Не знаю, за какие такие заслуги ей выделили отдельный лог файл, а cron, к примеру, нет.
- kern.log — лог сообщений ядра ubuntu, да и любой другой linux системы.
- maillog — сообщения почтовой системы. Обычно postfix или exim. Если на сервере ubuntu они не установлены, то и почтового лога не будет.
- dpkg.log — логирование работы пакетных менеджеров ubuntu. Обычно это apt или apt-get.
- lastlog и wtmp — информация о прошлых авторизациях пользователей.
Лог загрузки
Начнем с самого начала. В момент загрузки системы записывается вся основная информация, имеющая к ней отношение. Если у вас будут какие-то ошибки во время старта сервера, вы сможете их увидеть в этом логе. Посмотреть лог загрузки Ubuntu можно следующим образом.
sudo dmesg
У вас получится очень длинный вывод всего того, что происходило с системой на старте. Если ищите что-то конкретное, то можете сделать фильтрацию вывода с помощью grep. Допустим, вам надо узнать информацию только о диске.
sudo dmesg | grep sda
Вы увидите лог загрузки системы ubuntu, содержащий информацию только о диске sda. Аналогичным образом можно фильтровать вывод по другим темам. Например, посмотреть все ошибки, которые были во время загрузки.
sudo dmesg | grep error
И так далее. Информация, которую выводит команда dmesg, хранится в log файле /var/log/dmesg.
Логи авторизации, в том числе ssh
Для того, чтобы узнать, кто и когда проходил авторизацию на сервере ubuntu, можно воспользоваться логами из файла /var/log/auth.log. Авторизация по ssh там будет выглядеть следующим образом.
sshd[2774]: Accepted publickey for root from 21.17.214.129 port 2673 ssh2: RSA SHA256:MCDja9Ve7rYZCzeVGpYXpqRxfAanWwVkcd+lU3GS sshd[2774]: pam_unix(sshd:session): session opened for user root by (uid=0) systemd-logind[628]: New session 6 of user root.
Здесь мы видим ip адрес, с которого произошло подключение и слепок сертификата, так как аутентификация была произведена с его помощью. Если хотите повысить уровень логирования подключений по ssh и получать больше информации, то можете отредактировать конфигурационный файл sshd — /etc/ssh/sshd_config, добавив туда следующий параметр.
LogLevel VERBOSE
Не забудьте перезапустить службу sshd для принятия изменений:
sudo systemctl restart sshd
После этого логирование подключений по ssh будет более подробное.
Лог локального входа в ubuntu тоже хранится в файле auth.log. Информация о подключении через консоль выглядит следующим образом.
login[680]: pam_unix(login:session): session opened for user root by LOGIN(uid=0) systemd-logind[628]: New session 9 of user root. login[3094]: ROOT LOGIN on '/dev/tty1'
Устройство /dev/tty1 говорит о том, что вход локальный.
Вы можете быстро посмотреть информацию о последних входах в систему с помощью команды last. Эта информация хранится в бинарном логе /var/log/lastlog.
Примерно то же самое можно увидеть с помощью utmpdump.
sudo utmpdump /var/log/wtmp
Логи ошибок в Ubuntu
Рассмотрим теперь вопрос с расположением лога ошибок в Ubuntu. Как такового отдельного error log в традиционных linux системах нет. И Убунта тут не исключение. Ошибки придется искать по системным и программным логам выборкой ключевых слов. Обычно используют следующие фразы:
- error или err
- critical или crit
- debug
- warn
Например, посмотрим в логе загрузки dmesg все сообщения уровня предупреждений (warn).
sudo dmesg -l warn
А теперь проверим ошибки в системном логе.
sudo cat /var/log/syslog | grep error
Видим некоторые ошибки в службе systemd-resolved.
Cron logs
Часто хочется проверить лог запуска периодических заданий cron. В Ubuntu, как мне кажется, сделали не удобно. По умолчанию, cron logs не выделены в отдельный файл. Искать их стоит в общем системном логе syslog. Например, в Centos существует отдельный лог-файл /var/log/cron, где собрана вся информация о запущенных заданиях. Предлагаю сделать так же в Ubuntu.
Для этого открываем конфигурационный файл /etc/rsyslog.d/50-default.conf и добавляем туда следующую информацию.
cron.* /var/log/cron.log
По умолчанию, она присутствует в конфиге, но закомментирована. Вам нужно убрать # в начале строки, чтобы раскомментировать ее. Так же я рекомендую сделать так, чтобы эти логи не дублировались в общий системный лог. Для этого немного измените следующую строку.
*.*;auth,authpriv.none,cron.none -/var/log/syslog
Я добавил в нее cron.none, чтобы логи cron не писались больше в системный лог syslog. После этого перезапустите службы rsyslog и cron и проверяйте изменения.
sudo systemctl restart rsyslog sudo systemctl restart cron
Проверяем cron.log
sudo cat /var/log/cron.log
Теперь у нас все логи Cron в Ubuntu будут в отдельном файле.
Лог действий пользователя
Мне часто задают вопросы, как посмотреть лог действий пользователя в системе или как узнать, какие программы он запускал. По умолчанию, такие действия не логируются в ubuntu. Для этого нужно устанавливать какое-то дополнительное программное обеспечение. Я даже не знаю, кто умеет это делать. Обычно если надо фиксировать действия пользователя, включается лог работы sudo.
Для того, чтобы включить логирование действий пользователя через sudo, редактируем файл /etc/sudoers. Добавляем туда строку.
Defaults logfile=/var/log/sudo.log
Теперь выполните какую-нибудь команду через sudo.
sudo cat /var/log/cron.log
Проверяем sudo.log.
Nov 25 23:10:36 : root : TTY=pts/3 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/cat /var/log/cron.log
Выполненная команда пользователя сохранена в логе sudo.log. Теперь никто не сможет выполнить незаметно административные действия на сервере. Конечно, человек с полными правами сможет изменить любой лог файл, удалив свои действия при желании. Для этого важные логи нужно отправлять куда-то в другое место, но это уже тема отдельной статьи.
На сегодня по логам в Ubuntu у меня все. Желаю вам логов без ошибок и вечного аптайма (шутка, надо ставить обновы и перезагружаться).
Системные администраторы, да и обычные пользователи Linux, часто должны смотреть лог файлы для устранения неполадок. На самом деле, это первое, что должен сделать любой сисадмин при возникновении любой ошибки в системе.
Сама операционная система Linux и работающие приложения генерируют различные типы сообщений, которые регистрируются в различных файлах журналов. В Linux используются специальное программное обеспечение, файлы и директории для хранения лог файлов. Знание в каких файлах находятся логи каких программ поможет вам сэкономить время и быстрее решить проблему. В этой статье мы рассмотрим основные части системы логирования в Linux, файлы логов, а также утилиты, с помощью которых можно посмотреть логи Linux.
Расположение логов по умолчанию
Большинство файлов логов Linux находятся в папке /var/log/ вы можете список файлов логов для вашей системы с помощью команды ls:
ls -l /var/log/
Ниже мы рассмотрим 20 различных файлов логов Linux, размещенных в каталоге /var/log/. Некоторые из этих логов встречаются только в определенных дистрибутивах, например, dpkg.log встречается только в системах, основанных на Debian.
- /var/log/messages — содержит глобальные системные логи Linux, в том числе те, которые регистрируются при запуске системы. В этот лог записываются несколько типов сообщений: это почта, cron, различные сервисы, ядро, аутентификация и другие.
- /var/log/dmesg — содержит сообщения, полученные от ядра. Регистрирует много сообщений еще на этапе загрузки, в них отображается информация об аппаратных устройствах, которые инициализируются в процессе загрузки. Можно сказать это еще один лог системы Linux. Количество сообщений в логе ограничено, и когда файл будет переполнен, с каждым новым сообщением старые будут перезаписаны. Вы также можете посмотреть сообщения из этого лога с помощью команды dmseg.
- /var/log/auth.log — содержит информацию об авторизации пользователей в системе, включая пользовательские логины и механизмы аутентификации, которые были использованы.
- /var/log/boot.log — Содержит информацию, которая регистрируется при загрузке системы.
- /var/log/daemon.log — Включает сообщения от различных фоновых демонов
- /var/log/kern.log — Тоже содержит сообщения от ядра, полезны при устранении ошибок пользовательских модулей, встроенных в ядро.
- /var/log/lastlog — Отображает информацию о последней сессии всех пользователей. Это нетекстовый файл, для его просмотра необходимо использовать команду lastlog.
- /var/log/maillog /var/log/mail.log — журналы сервера электронной почты, запущенного в системе.
- /var/log/user.log — Информация из всех журналов на уровне пользователей.
- /var/log/Xorg.x.log — Лог сообщений Х сервера.
- /var/log/alternatives.log — Информация о работе программы update-alternatives. Это символические ссылки на команды или библиотеки по умолчанию.
- /var/log/btmp — лог файл Linux содержит информацию о неудачных попытках входа. Для просмотра файла удобно использовать команду last -f /var/log/btmp
- /var/log/cups — Все сообщения, связанные с печатью и принтерами.
- /var/log/anaconda.log — все сообщения, зарегистрированные при установке сохраняются в этом файле
- /var/log/yum.log — регистрирует всю информацию об установке пакетов с помощью Yum.
- /var/log/cron — Всякий раз когда демон Cron запускает выполнения программы, он записывает отчет и сообщения самой программы в этом файле.
- /var/log/secure — содержит информацию, относящуюся к аутентификации и авторизации. Например, SSHd регистрирует здесь все, в том числе неудачные попытки входа в систему.
- /var/log/wtmp или /var/log/utmp — системные логи Linux, содержат журнал входов пользователей в систему. С помощью команды wtmp вы можете узнать кто и когда вошел в систему.
- /var/log/faillog — лог системы linux, содержит неудачные попытки входа в систему. Используйте команду faillog, чтобы отобразить содержимое этого файла.
- /var/log/mysqld.log — файлы логов Linux от сервера баз данных MySQL.
- /var/log/httpd/ или /var/log/apache2 — лог файлы linux11 веб-сервера Apache. Логи доступа находятся в файле access_log, а ошибок в error_log
- /var/log/lighttpd/ — логи linux веб-сервера lighttpd
- /var/log/conman/ — файлы логов клиента ConMan,
- /var/log/mail/ — в этом каталоге содержатся дополнительные логи почтового сервера
- /var/log/prelink/ — Программа Prelink связывает библиотеки и исполняемые файлы, чтобы ускорить процесс их загрузки. /var/log/prelink/prelink.log содержит информацию о .so файлах, которые были изменены программой.
- /var/log/audit/— Содержит информацию, созданную демоном аудита auditd.
- /var/log/setroubleshoot/ — SE Linux использует демон setroubleshootd (SE Trouble Shoot Daemon) для уведомления о проблемах с безопасностью. В этом журнале находятся сообщения этой программы.
- /var/log/samba/ — содержит информацию и журналы файлового сервера Samba, который используется для подключения к общим папкам Windows.
- /var/log/sa/ — Содержит .cap файлы, собранные пакетом Sysstat.
- /var/log/sssd/ — Используется системным демоном безопасности, который управляет удаленным доступом к каталогам и механизмами аутентификации.
Чтобы посмотреть логи на Linux удобно использовать несколько утилит командной строки Linux. Это может быть любой текстовый редактор, или специальная утилита. Скорее всего, вам понадобятся права суперпользователя для того чтобы посмотреть логи в Linux. Вот команды, которые чаще всего используются для этих целей:
- less;
- more;
- cat;
- head;
- grep;
- tail;
- zcat;
- zgrep;
- zmore;
- vi;
- nano.
Я не буду останавливаться подробно на каждой из этих команд, поскольку большинство из них уже подробно рассмотрены на нашем сайте. Но приведу несколько примеров. Просмотр логов Linux выполняется очень просто:
Смотрим лог /var/log/dmesg, с возможностью прокрутки:
less /var/log/dmesg
Просмотр логов Linux, в реальном времени:
tail -f /var/log/dmesg
Открываем лог файл dmesg:
cat /var/log/dmesg
Первые строки dmesg:
head /var/log/dmesg
Выводим только ошибки из /var/log/messages:
grep -i error /var/log/dmesg
Кроме того, посмотреть логи на linux можно и с помощью графических утилит. Программа Журналы может быть использована для удобного просмотра и отслеживания системных журналов на ноутбуке или персональном компьютере с Linux.
Вы можете установить программу в любой системе с установленным X сервером. Также для просмотра логов может использоваться любой графический тестовый редактор.
Кроме того, у каждого сервиса есть свой лог файл, который можно посмотреть с помощью утилиты journalctl.
Выводы
В каталоге /var/log вы можете найти всю необходимую информацию о работе Linux. Из сегодняшней статьи вы достаточно узнали, чтобы знать где искать, и что искать. Теперь просмотр логов в Linux не вызовет у вас проблем. Если остались вопросы, задавайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
Время на прочтение
6 мин
Количество просмотров 117K
Journalctl — отличный инструмент для анализа логов, обычно один из первых с которым знакомятся начинающие администраторы linux систем. Встроенные возможности ротации, богатые возможности фильтрации и возможность просматривать логи всех systemd unit-сервисов одним инструментом очень удобны и заметно облегчают работу системным администраторам.
Эта статья рассматривает основные возможности утилиты journalctl и различные варианты ее применения. С помощью journalctl можно просматривать логи системы, чтобы решить возникшие проблемы на рабочей станции или сервере использующие дистрибутив linux с демоном инициализации systemd, де-факто уже ставшим стандартом в современных Linux-системах, например: RHEL, CentOS, Fedora, Debian и многих других.
Существует мнение, что systemd не так уж и хорош — он нагружает систему и это все еще предмет для споров на сегодняшний день, но нельзя отрицать, что он предоставляет прекрасный набор инструментов для управления системой и поиска проблем. Представьте, что вам приходится иметь дело с проблемным сервером, который даже не загружается — в таком случае можно загрузиться с live-дистрибутива, смонтировать системный раздел и просмотреть логи systemd, чтобы понять, в чем проблема.
Systemd
Systemd состоит из трех основных компонентов:
- systemd — менеджер системы и сервисов
- systemctl — утилита для просмотра и управление статусом сервисов
- systemd-analyze — предоставляет статистику по процессу загрузки системы, проверяет корректность unit-файлов и так же имеет возможности отладки systemd
Journald
Journald — системный демон журналов systemd. Systemd спроектирован так, чтобы централизованно управлять системными логами от процессов, приложений и т.д. Все такие события обрабатываются демоном journald, он собирает логи со всей системы и сохраняет их в бинарных файлах.
Преимуществ централизованного логирования событий в бинарном формате достаточно много, например системные логи можно транслировать в различные форматы, такие как простой текст, или в JSON, при необходимости. Так же довольно просто можно отследить лог вплоть до одиночного события используя фильтры даты и времени.
Файлы логов journald могут собирать тысячи событий и они обновляются с каждым новым событием, поэтому если ваша Linux-система работает достаточно долго — размер файлов с логами может достигать несколько гигабайт и более. Поэтому анализ таких логов может происходить с задержками, в таком случае, при анализе логов можно фильтровать вывод, чтобы ускорить работу.
Файл конфигурации journald
Файл конфигурации можно найти по следующему пути: /etc/systemd/journald.conf, он содержит различные настройки journald, я бы не рекомендовал изменять этот файл, если вы точно не уверены в том, что делаете.
Каталог с журналом journald располагается /run/log/journal (в том случае, если не настроено постоянное хранение журналов, но об этом позже).
Файлы хранятся в бинарном формате, поэтому нормально их просмотреть с помощью cat или nano, как привыкли многие администраторы — не получится.
Использование journalctl для просмотра и анализа логов
Основная команда для просмотра:
# journalctl
Она выведет все записи из всех журналов, включая ошибки и предупреждения, начиная с того момента, когда система начала загружаться. Старые записи событий будут наверху, более новые — внизу, вы можете использовать PageUp и PageDown чтобы перемещаться по списку, Enter — чтобы пролистывать журнал построчно и Q — чтобы выйти.
По умолчанию journalctl выводит время событий согласно настроенного в вашей системе часового пояса, также journalctl позволяет просмотреть логи с временем UTC (в этом стандарте времени сохраняются события внутри файлов journald), для этого можно использовать команду:
# journalctl --utc
Фильтрация событий по важности
Система записывает события с различными уровнями важности, какие-то события могут быть предупреждением, которое можно проигнорировать, какие-то могут быть критическими ошибками. Если мы хотим просмотреть только ошибки, игнорируя другие сообщения, введем команду с указанием кода важности:
# journalctl -p 0
Для уровней важности, приняты следующие обозначения:
- 0: emergency (неработоспособность системы)
- 1: alerts (предупреждения, требующие немедленного вмешательства)
- 2: critical (критическое состояние)
- 3: errors (ошибки)
- 4: warning (предупреждения)
- 5: notice (уведомления)
- 6: info (информационные сообщения)
- 7: debug (отладочные сообщения)
Когда вы указываете код важности, journalctl выведет все сообщения с этим кодом и выше. Например если мы укажем опцию -p 2, journalctl покажет все сообщения с уровнями 2, 1 и 0.
Настройка хранения журналов
По умолчанию journald перезаписывает свои журналы логов при каждой перезагрузке, и вызов journalctl выведет журнал логов начиная с текущей загрузки системы.
Если необходимо настроить постоянное сохранение логов, потребуется отдельно это настроить, т.к. разработчики отказались от постоянного хранения всех журналов, чтобы не дублировать rsyslog.
Когда в конфигурационном файле /etc/systemd/journald.conf параметру Storage= задано значение auto) и каталога /var/log/journal/ не существует, журнал будет записываться в /run/log/journal без сохранения между перезагрузками, если /var/log/journal/ существует, журналы будут сохраняться в нем, на постоянной основе, но если каталог будет удален, systemd не пересоздаст его автоматически и вместо этого будет вести журнал снова в /run/systemd/journal без сохранения. Каталог может быть пересоздан в таком случае, если добавить Storage=persistent в journald.conf и перезапустить systemd-journald.service (или перезагрузиться).
Создадим каталог для хранения журналов, установим необходимые атрибуты и перезапустим службу:
# mkdir /var/log/journal
# systemd-tmpfiles --create --prefix /var/log/journal
# systemctl restart systemd-journald
Просмотр журналов загрузки
Если journald был настроен на постоянное хранение журналов, мы можем просматривать журналы логов по каждой отдельной загрузке, следующая команда выведет список журналов:
# journalctl --list-boots
Первый номер показывает номер журнала, который можно использовать для просмотра журнала определенной сессии. Второй номер boot ID так же можно использовать для просмотра отдельного журнала.
Следующие две даты, промежуток времени в течении которого в него записывались логи, это удобно если вы хотите найти логи за определенный период.
Например, чтобы просмотреть журнал начиная с текущего старта системы, можно использовать команду:
# journalctl -b 0
А для того, чтобы просмотреть журнал предыдущей загрузки:
# journalctl -b -1
Просмотр журнала за определенный период времени
Journalctl позволяет использовать такие служебные слова как “yesterday” (вчера), “today” (сегодня), “tomorrow” (завтра), или “now” (сейчас).
Поэтому мы можем использовать опцию «—since» (с начала какого периода выводить журнал).
С определенной даты и времени:
# journalctl --since "2020-12-18 06:00:00"
С определенной даты и по определенное дату и время:
# journalctl --since "2020-12-17" --until "2020-12-18 10:00:00
Со вчерашнего дня:
# journalctl --since yesterday
С 9 утра и до момента, час назад:
# journalctl --since 09:00 --until "1 hour ago"
Просмотр сообщений ядра
Чтобы просмотреть сообщения от ядра Linux за текущую загрузку, используйте команду с ключом -k:
# journalctl -k
Просмотр журнала логов для определенного сервиса systemd или приложения
Вы можете отфильтровать логи по определенному сервису systemd. Например, что бы просмотреть логи от NetworkManager, можно использовать следующую команду:
# journalctl -u NetworkManager.service
Если нужно найти название сервиса, используйте команду:
# systemctl list-units --type=service
Так же можно просмотреть лог приложения, указав его исполняемый файл, например чтобы просмотреть все сообщения от nginx за сегодня, мы можем использовать команду:
# journalctl /usr/sbin/nginx --since today
Или указав конкретный PID:
# journalctl _PID=1
Дополнительные опции просмотра
Следить за появлением новых сообщений (аналог tail -f):
# journalctl -f
Открыть журнал «перемотав» его к последней записи:
# journalctl -e
Если в каталоге с журналами очень много данных, то фильтрация вывода journalctl может занять некоторое время, процесс можно значительно ускорить с помощью опции —file, указав journalctl только нужный нам журнал, за которым мы хотим следить:
journalctl --file /var/log/journal/e02689e50bc240f0bb545dd5940ac213/system.journal -f
По умолчанию journalctl отсекает части строк, которые не вписываются в экран по ширине, хотя иногда перенос строк может оказаться более предпочтительным. Управление этой возможностью производится посредством переменной окружения SYSTEMD_LESS, в которой содержатся опции, передаваемые в less (программу постраничного просмотра, используемую по умолчанию). По умолчанию переменная имеет значение FRSXMK, если убрать опцию S, строки не будут обрезаться.
Например:
SYSTEMD_LESS=FRXMK journalctl
Ограничение размера журнала
Если journald настроен что бы сохранять журналы после перезагрузки, то по умолчанию размер журнала ограничен 10% от объема файлового раздела и максимально может занять 4 Гб дискового пространства.
Максимальный объем журнала можно скорректировать, раскомментировав и отредактировав следующий параметр в файле конфигурации journald:
SystemMaxUse=50M
Удаление журналов
Удалить файлы архивных журналов, можно вручную с помощью rm или использовав journalctl.
Удалить журналы, оставив только последние 100 Мб:
# journalctl --vacuum-size=100M
Удалить журналы, оставив журналы только за последние 7 дней:
# journalctl --vacuum-time=7d
Заключение
Служба журналирования логов journald очень мощный и гибкий инструмент, и если вы знаете как его использовать, он может сделать вашу жизнь намного проще во время поиска причин проблем с системой или ее сервисами.
This tutorial explains the basic administration of a Linux server through system
logs. A system log is a file that contains information about the events that
happened on the system during runtime.
In this article, you will learn the following Linux logging basics:
- Where the Linux log files are stored, how are they formatted, and how to read them.
- How to read the most important logs (such as
syslog
). - How to configure the Ubuntu
syslog
daemon. - What Linux log rotation is all about and how to use the logrotate utility.
Prerequisites
Before proceeding with the rest of this tutorial, ensure that you have a basic
knowledge of working with the Linux command line. While many of the concepts
discussed in this article are general applicable to all Linux distributions,
we’ll be demonstrating them in Ubuntu only so ensure to set up an Ubuntu 20.04
server that includes a non-root user with sudo
access.
🔭 Want to centralize and monitor your Linux logs?
Head over to Logtail and start ingesting your logs in 5 minutes.
Step 1 — Finding Linux system logs
All Ubuntu system logs are stored in the /var/log
directory. Change into this
directory in the terminal using the command below:
You can view the contents of this directory by issuing the following command:
You should see a similar output to the following:
alternatives.log auth.log btmp cloud-init-output.log dmesg dpkg.log journal/ landscape/ private/ ubuntu-advantage-license-check.log ubuntu-advantage-timer.log unattended-upgrades/
apt/ bootstrap.log cloud-init.log dist-upgrade/ dmesg.0 faillog kern.log lastlog syslog ubuntu-advantage.log ufw.log wtmp
Let’s look at a few of the essential system log files that may be present in the
/var/log
directory and what they contain:
/var/log/syslog
: stores general information about any global activity in the
system./var/log/auth.log
: keeps track of all security-related actions (login,
logout, or root user activity)./var/log/kern.log
: stores information about events originating from the
Linux kernel./var/log/boot.log
: stores system startup messages./var/log/dmesg
: contains messages related to device drivers./var/log/faillog
: keeps track of failed logins, which comes in handy when
investigating attempted security breaches.
The /var/log
directory is also used to store various application logs. For
example, if your distribution is bundled with Apache or MySQL, or installed
later, their log files will also be found here.
Step 2 — Viewing Linux log file contents
Log files contain a large amount of information that are useful for monitoring
or analyzing activities performed by the system or a specific application.
Therefore, a Linux server administrator must learn the art of reading and
understanding the various messages present in log files to effectively diagnose
or troubleshoot an issue.
Before we can read log files, we ought to know how they are formatted. Let’s
review two basic approaches to log file formatting and storage: plain text and
binary files.
Plaintext log files
These logs are plain text files with a standardized content format. Ubuntu uses
a log template called
RSYSLOG_TraditionalFileFormat.
This log format consists of four main fields with a space delimiter:
- The timestamp indicates the time when a log entry was created in the
formatMMM dd HH:mm:ss
(e.g.Sep 28 19:00:00
). Notice that this format
does not include a year. - Hostname is the host or system that originally create the message.
- Application is the application that created the message.
- Message contains the actual details of an event.
Let’s go ahead and review some log files in the plaintext format. Run the
command below to print the contents of the /var/log/syslog
file with the
tail
utility:
sudo tail /var/log/syslog
This outputs the last 10 lines of the file:
Mar 23 12:38:09 peter dbus-daemon[1757]: [session uid=1000 pid=1757] Activating via systemd: service name='org.freedesktop.Tracker1' unit='tracker-store.service' requested by ':1.1' (uid=1000 pid=1754 comm="/usr/libexec/tracker-miner-fs " label="unconfined")
Mar 23 12:38:09 peter systemd[1743]: Starting Tracker metadata database store and lookup manager...
Mar 23 12:38:09 peter dbus-daemon[1757]: [session uid=1000 pid=1757] Successfully activated service 'org.freedesktop.Tracker1'
Mar 23 12:38:09 peter systemd[1743]: Started Tracker metadata database store and lookup manager.
Mar 23 12:38:40 peter tracker-store[359847]: OK
Mar 23 12:38:40 peter systemd[1743]: tracker-store.service: Succeeded.
Mar 23 12:39:01 peter CRON[359873]: (root) CMD ( [ -x /usr/lib/php/sessionclean ] && if [ ! -d /run/systemd/system ]; then /usr/lib/php/sessionclean; fi)
Mar 23 12:39:23 peter systemd[1]: Starting Clean php session files...
Mar 23 12:39:23 peter systemd[1]: phpsessionclean.service: Succeeded.
Mar 23 12:39:23 peter systemd[1]: Finished Clean php session files.
You’ll notice that that each record in this file is formatted in the manner
described earlier. For example, the last record has its timestamp
as Mar 23
12:39:23, hostname
as peter, application
as systemd[1] and message
as
Finished Clean php session files.
If you want to view the entire log file, you can use the cat
utility or any
text editor such as nano
or vim
.
Binary log files
While plaintext is the dominant storage format for log files, you will also
encounter binary log files that cannot be read with a normal text editor. The
/var/log
directory contains multiple binary files that are related to the user
authorization:
/var/log/utmp
: tracks users that are currently logged into the system./var/log/wtmp
: tracks previously logged in users. It contains a past data
fromutmp
./var/log/btmp
: tracks failed login attempts.
For these binary logs, special command-line tools are used to display the
relevant information in human-readable form. For example, to review the contents
of the /var/log/utmp
file, run the who
utility with -H
option (this option
causes column labels to be printed in the output table):
You’ll see the program’s output appear on the screen:
NAME LINE TIME COMMENT
george pts/0 2021-03-21 15:29 (2001:67c:1220:80c:b1:a84e:69ee:f530)
willie pts/1 2021-03-21 07:20 (adsl-dyn22.78-98-29.t-com.sk)
bonnie pts/2 2021-03-21 10:31 (2001:67c:1220:80c:b1:a84e:69ee:f530)
peter pts/6 2021-03-21 14:37 (100.64.97.50)
...
The output above describes all the currently logged in users, the time of login
and their host machine’s IP address.
You can also review the contents of the /var/log/wtmp
binary file through the
last
command as shown below:
You’ll see the program’s output appear on the screen:
peter :1 Sat Mar 13 08:06 still logged in
reboot system boot Sat Mar 13 08:06 still running
peter :1 Fri Mar 12 07:42 - down (1+00:22)
reboot system boot Fri Mar 12 07:42 - 08:05 (1+00:23)
peter :1 Sun Mar 7 11:20 - down (4+20:21)
reboot system boot Sun Mar 7 11:20 - 07:41 (4+20:21)
peter :1 Fri Mar 5 08:02 - crash (2+03:17)
reboot system boot Fri Mar 5 08:01 - 07:41 (6+23:39)
peter :0 Tue Mar 2 08:38 - crash (2+23:23)
reboot system boot Tue Mar 2 08:38 - 07:41 (9+23:03)
peter :1 Thu Feb 25 11:44 - down (4+20:53)
reboot system boot Thu Feb 25 11:44 - 08:37 (4+20:53)
wtmp begins Thu Feb 25 11:43:23 2021
The output shows a table where the first column refers to the user name (the
pseudo-user reboot is recorded each time when the system is rebooted). The third
field refers to the login timestamp, and the last column shows the session
duration.
To review the /var/log/btmp
file (containing failed login attempts), execute
the lastb
command with sudo
privileges:
You’ll see the program’s output appear on the screen:
falcon tty3 Thu Feb 12 07:10 - 07:10 (00:00)
ruby tty1 Thu Feb 12 07:09 - 07:09 (00:00)
sergio tty1 Thu Feb 12 07:09 - 07:09 (00:00)
btmp begins Thu Feb 25 11:43:32 2021
The output shows users that failed to login with the corresponding timestamp.
Step 3 — Examining the syslog deamon configuration
All system logs are created and maintained by a background process called a
daemon. The traditional Linux daemon for logging is syslogd
. However, Ubuntu
20.04 uses a daemon called rsyslogd
which is a superset of syslogd
. It uses
a special configuration file (/etc/rsyslog.conf
) that specifies the logging
rules.
Go ahead and print the contents of the /etc/rsyslog.conf
file with the cat
command:
This command prints the entire content of this configuration file, but we’re
only going to show a truncated output here:
[label /etc/rsyslog.conf]
. . .
###########################
#### GLOBAL DIRECTIVES ####
###########################
#
# Use traditional timestamp format.
# To enable high precision timestamps, comment out the following line.
#
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
# Filter duplicated messages
$RepeatedMsgReduction on
#
# Set the default permissions for all log files.
#
$FileOwner syslog
$FileGroup adm
$FileCreateMode 0640
$DirCreateMode 0755
$Umask 0022
$PrivDropToUser syslog
$PrivDropToGroup syslog
#
# Where to place spool and state files
#
$WorkDirectory /var/spool/rsyslog
#
# Include all config files in /etc/rsyslog.d/
#
$IncludeConfig /etc/rsyslog.d/*.conf
This file contains a lot of information, but we’ll focus on two configuration
details. Firstly, a variable called $ActionFileDefaultTemplate
defines the
syslog record format as described in Step 2. You can change the value of this
variable if the default log format is unsuitable for you. Secondly, the last
line in the file defines a variable called $IncludeConfig
that specifies the
directory for additional configuration files.
In Ubuntu, all additional Rsyslog rules are placed in the
/etc/rsyslog.d/50-default.conf
file by default. Go ahead and examine the
contents of this file with the head
utility (the -n 15
option specifies that
only the first 15 lines should be printed):
head -n 15 /etc/rsyslog.conf/50-default.conf
You’ll see the program’s output appear on the screen:
# Default rules for rsyslog.
#
# For more information see rsyslog.conf(5) and /etc/rsyslog.conf
#
# First some standard log files. Log by facility.
#
auth,authpriv.* /var/log/auth.log
*.*;auth,authpriv.none -/var/log/syslog
#cron.* /var/log/cron.log
#daemon.* -/var/log/daemon.log
kern.* -/var/log/kern.log
#lpr.* -/var/log/lpr.log
mail.* -/var/log/mail.log
#user.* -/var/log/user.log
The output contains rsyslogd
configuration rules. Each non-empty line (or line
that does not start with the #
character) defines a rule. The rule definition
starts with a selector followed by one or more spaces and an action field:
- The selector specifies the facility with a corresponding priority. For
example, the*
selector refers to all facilities or priorities. - The action field of a selector usually references a log file.
Step 4 — Rotating log files in Linux
The size of log file must be controlled because they always grow over time. Each
system has limited resources and logs that are too large can lead to performance
and memory problems, not to mention the loss of storage space. Linux
distributions typically solve this problem through the concept of log rotation
which continuously repeats the following actions:
- Instead of continuously writing to log file as it grows larger, the file name
is changed to one with a version suffix, and creates a brand new file is
created for new log entries. This means a log file has multiple backups which
are optionally compressed. - When the backup files reaches a specified number, the system deletes the
oldest ones.
Let’s view an example of rotating log files in Linux. Execute the ls
command
with following options:
ls -l -h -t /var/log/syslog*
The -l
option outputs a listing that includes various metadata about a file,
the -h
option prints the file size in human-readable form, and the -t
option
sorts the listing by modification time (newest first). The /var/log/syslog*
argument specifies that only files in the /var/log
directory with the syslog
prefix should be included in the output.
You’ll see the program’s output appear on the screen:
-rw-r----- 1 syslog adm 47K mar 30 09:49 /var/log/syslog
-rw-r----- 1 syslog adm 3,5G mar 30 07:45 /var/log/syslog.1.gz
-rw-r----- 1 syslog adm 1,6M mar 29 10:06 /var/log/syslog.2.gz
-rw-r----- 1 syslog adm 29K mar 28 07:49 /var/log/syslog.3.gz
-rw-r----- 1 syslog adm 54K mar 27 08:08 /var/log/syslog.4.gz
-rw-r----- 1 syslog adm 6,4M mar 26 07:35 /var/log/syslog.5.gz
-rw-r----- 1 syslog adm 31K mar 25 08:01 /var/log/syslog.6.gz
This output describes all the versions of the syslog
file. Typically, it is
the biggest log file on the system because, as explained earlier, it records
almost every event that occurs in the system. The older versions are labelled
with a version suffix (e.g. syslog.6.gz
is the oldest syslog backup).
Notice that the backup files are all compressed with the standard GNU zip
compression algorithm. (as evidenced by the .gz
extension). This helps with
space savings since log files can grow to the size of gigabytes (in our example
the biggest file is 3.5 GB). You’ll also notice that these files cover a time
interval of only six days.
Step 5 — Configuring the logrotate daemon
Log rotation is maintained by a system daemon called logrotate
. Similar to the
rsyslogd
utility, this daemon uses a special configuration file called
logrotate.conf
in the /etc
directory.
Go ahead and display the contents of the logrotate
config file with cat
utility:
This command prints the entire contents of the configuration file to the screen:
# see "man logrotate" for details
# rotate log files weekly
weekly
# use the adm group by default, since this is the owning group
# of /var/log/syslog.
su root adm
# keep 4 weeks worth of backlogs
rotate 4
# create new (empty) log files after rotating old ones
create
# use date as a suffix of the rotated file
#dateext
# uncomment this if you want your log files compressed
#compress
# packages drop log rotation information into this directory
include /etc/logrotate.d
# system-specific logs may be also be configured here.
The output describes the global configuration for logrotate
. In our example,
the log files are rotated weekly, the system keeps four rotation backups, and
compression is turned off. However, this is the most general configuration for
any log. We can also set up a more specific configuration for a particular log
file. In Ubuntu, the configuration for specific logs are placed in the
/etc/logrotate.d
directory by default (you’ll notice the presence of this
directory in /etc/logrotate.conf
).
Let’s view the contents of the /etc/logrotate.d
directory by executing the
ls
command:
The output below describes all the utilities that have a specific log rotation
config:
alternatives bootlog dpkg ubuntu-advantage-tools
apache2 btmp ppp ufw
apport certbot rsyslog unattended-upgrades
apt cups-daemon speech-dispatcher wtmp
You’ll notice that the rsyslog
daemon has its own log rotation configuration
file. Go ahead and display the first 15 lines of the rsyslog
file with the
head
utility:
head -n 15 /etc/logrotate.d/rsyslog
You’ll see the following output on the screen:
/var/log/syslog
{
rotate 7
daily
missingok
notifempty
delaycompress
compress
postrotate
/usr/lib/rsyslog/rsyslog-rotate
endscript
}
/var/log/mail.info
/var/log/mail.warn
This output shows that the syslog
file is rotated daily, and that seven
compressed backups are kept before older ones are deleted.
You can force logrotate
to rotate a log file immediately by executing
following the command:
sudo logrotate -fv /etc/logrotate.conf
The -f
option forces immediate rotation and the -v
option turns on verbose
mode (it will display messages during rotation). The execution of this command
shows the following output (truncated to save space):
reading config file /etc/logrotate.conf
including /etc/logrotate.d
reading config file alternatives
reading config file apache2
reading config file apport
reading config file apt
reading config file bootlog
reading config file btmp
reading config file certbot
reading config file cups-daemon
reading config file dpkg
reading config file ppp
reading config file rsyslog
reading config file speech-dispatcher
reading config file ubuntu-advantage-tools
reading config file ufw
reading config file unattended-upgrades
reading config file wtmp
. . .
The beginning of the output shows that the logrotate
daemon reads all its
configuration files first before proceeding. The entire output is very long
because it prints every single detail of the rotation process.
Conclusion
In this tutorial, you’ve learnt the basics of system logs in Linux and how to
read and understand them. We discussed where the logs are typically placed and
the different log formats you will likely encounter. We also covered the
rsyslogd
utility, which is responsible for maintaining log files in Ubuntu
before discussing log rotation and how to use the logrotate
utility to keep
log files small and manageable. To learn more about all the utilities described
in this article, explore the
Rsyslog server article and the
Logrotate article in
the Logging guides.
Thanks for reading!
Article by
Ayooluwa Isaiah
Ayo is the Head of Content at Better Stack. His passion is simplifying and communicating complex technical ideas effectively. His work was featured on several esteemed publications including LWN.net, Digital Ocean, and CSS-Tricks. When he’s not writing or coding, he loves to travel, bike, and play tennis.
Centralize all your logs into one place.
Analyze, correlate and filter logs with SQL.
Create actionable
dashboards.
Share and comment with built-in collaboration.
Got an article suggestion?
Let us know
Next article
A Complete Guide to Managing Log Files with Logrotate
Learn how to use the Logrotate utility to set up automatic rotation, compression and deletion of log files in Linux
→
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.