Системные администраторы, да и обычные пользователи 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.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
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.
So, if there is some problem with my computer, be it hardware or software, what are the major log files and where are they located?
Also, is there a generic location where log files of the other packages might be located?
asked Sep 10, 2012 at 18:37
greengreen
14.2k7 gold badges41 silver badges64 bronze badges
1
All log files are located in /var/log
directory. In that directory, there are specific files for each type of logs. For example, system logs, such as kernel activities are logged in syslog
file.
Some of the most common log files in that directory is :
-
In directory
apt
there is a filehistory.log
which saves all the package installation and removal information even the initial system build as Live CD. You can open this file to see this very interesting file. -
In directory
dist-upgrade
there is a fileapt.log
which logs the information during distribution upgrades -
In directory
installer
the log files which are created during installation can be found. -
There is an
apport.log
file which saves information about crashes in your system and reporting them. -
The file
auth.log
includes information about the authentication activities such as when you authenticate as root user via sudo. -
The file
dpkg.log
saves the low level details of package installation and removal related withdpkg
. You might be aware that theapt
system depends ondpkg
for package installation and removal. -
boot.log
includes information of each booting. -
kern.log
saves kernel information such as warnings, errors etc. -
alternatives.log
includes the history of all the alternatives set by various packages and their removal viaupdate-alternatives
command. -
Another important log file is
Xorg.log
which include information about the graphics driver, its failures, warnings etc.
Some other types of Log files may be there depending on your installed packages. For example, My system also includes a log files epoptes.log
which will only be there if you install epoptes
package.
Changes after systemd
With the advent of systemd
, logging is mostly handled by journalctl
utility and store the logs in binary format in /var/lib/systemd/catalog/database
file. This file enumerates all logs including kernel, boot and application logs and provides required logs via journalctl
utility.
Here is a good article on journalctl
on how you can use it to fetch required log info.
https://www.digitalocean.com/community/tutorials/how-to-use-journalctl-to-view-and-manipulate-systemd-logs#setting-the-system-time
answered Sep 10, 2012 at 18:51
AnwarAnwar
75.4k31 gold badges191 silver badges308 bronze badges
1
In the screenshot below most of the important logs from /var/log
are shown. In that location there are often other folders from other applications such as samba
or apache2
if you have it installed.
To watch a log in real time you can use gnome-system-log
or, for example, use
tail -f /var/log/kern.log
All logs can be analysed more easily either with the filter option in gnome-system-log
or by using grep
to search for a particular term. For example, if I wanted to find references to my SiS hardware, I could enter:
grep -i SiS /var/log/kern.log
Most of the logs in the screenshot are self-explanatory, however, here’s a few quick notes:
auth.log
deals with all privileged actions such as when you use sudo in the terminal or run gui programs such as synaptic.kern.log
records all kernel activity and can be useful for diagnosing errors with hardware.dpkg.log
is a very detailed account of packages installedsyslog
contains both information from the kernel and OS informationxorg.log
contains information on the (largely automatic) setup of your displayudev
is particularly useful as it contains some details about the setup of hardware that could be useful to record for the future.history.log
(as seen in the screenshot) is from/var/log/apt
and contains the history of your updates and installations.
answered Sep 10, 2012 at 19:08
2
Время на прочтение
6 мин
Количество просмотров 411K
Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе Linux, который никогда не читал лог файлы. Операционная система и работающие приложения постоянно создают различные типы сообщений, которые регистрируются в различных файлах журналов. Умение определить нужный файл журнала и что искать в нем поможет существенно сэкономить время и быстрее устранить ошибку.
Журналирование является основным источником информации о работе системы и ее ошибках. В этом кратком руководстве рассмотрим основные аспекты журналирования операционной системы, структуру каталогов, программы для чтения и обзора логов.
Основные лог файлы
Все файлы журналов, можно отнести к одной из следующих категорий:
- приложения;
- события;
- службы;
- системный.
Большинство же лог файлов содержится в директории /var/log
.
- /var/log/syslog или /var/log/messages содержит глобальный системный журнал, в котором пишутся сообщения с момента запуска системы, от ядра Linux, различных служб, обнаруженных устройствах, сетевых интерфейсов и много другого.
- /var/log/auth.log или /var/log/secure — информация об авторизации пользователей, включая удачные и неудачные попытки входа в систему, а также задействованные механизмы аутентификации.
- /var/log/dmesg — драйвера устройств. Одноименной командой можно просмотреть вывод содержимого файла. Размер журнала ограничен, когда файл достигнет своего предела, старые сообщения будут перезаписаны более новыми. Задав ключ
--level=
можно отфильтровать вывод по критерию значимости.
Поддерживаемые уровни журналирования (приоритеты):
emerg - система неиспользуемая
alert - действие должно быть произведено немедленно
crit - условия критичности
err - условия ошибок
warn - условия предупреждений
notice - обычные, но значимые условия
info - информационный
debug - отладочные сообщения
(5:520)$ dmesg -l err
[1131424.604352] usb 1-1.1: 2:1: cannot get freq at ep 0x1
[1131424.666013] usb 1-1.1: 1:1: cannot get freq at ep 0x81
[1131424.749378] usb 1-1.1: 1:1: cannot get freq at ep 0x81
- /var/log/alternatives.log — Вывод программы
update-alternatives
, в котором находятся символические ссылки на команды или библиотеки по умолчанию. - /var/log/anaconda.log — Записи, зарегистрированные во время установки системы.
- /var/log/audit — Записи, созданные службой аудита
auditd
. - /var/log/boot.log — Информация, которая пишется при загрузке операционной системы.
- /var/log/cron — Отчет службы
crond
об исполняемых командах и сообщения от самих команд. - /var/log/cups — Все, что связано с печатью и принтерами.
- /var/log/faillog — Неудачные попытки входа в систему. Очень полезно при проверке угроз в системе безопасности, хакерских атаках, попыток взлома методом перебора. Прочитать содержимое можно с помощью команды
faillog
. - var/log/kern.log — Журнал содержит сообщения от ядра и предупреждения, которые могут быть полезны при устранении ошибок пользовательских модулей встроенных в ядро.
- /var/log/maillog/ или /var/log/mail.log — Журнал почтового сервера, используемого на ОС.
- /var/log/pm-powersave.log — Сообщения службы экономии заряда батареи.
- /var/log/samba/ — Логи файлового сервера
Samba
, который используется для доступа к общим папкам Windows и предоставления доступа пользователям Windows к общим папкам Linux. - /var/log/spooler — Для представителей старой школы, содержит сообщения USENET. Чаще всего бывает пустым и заброшенным.
- /var/log/Xorg.0.log — Логи X сервера. Чаще всего бесполезны, но если в них есть строки начинающиеся с EE, то следует обратить на них внимание.
Для каждого дистрибутива будет отдельный журнал менеджера пакетов.
- /var/log/yum.log — Для программ установленных с помощью
Yum
в RedHat Linux. - /var/log/emerge.log — Для
ebuild
-ов установленных изPortage
с помощьюemerge
в Gentoo Linux. - /var/log/dpkg.log — Для программ установленных с помощью
dpkg
в Debian Linux и всем семействе родственных дистрибутивах.
И немного бинарных журналов учета пользовательских сессий.
- /var/log/lastlog — Последняя сессия пользователей. Прочитать можно командой
last
. - /var/log/tallylog — Аудит неудачных попыток входа в систему. Вывод на экран с помощью утилиты
pam_tally2
. - /var/log/btmp — Еже один журнал записи неудачных попыток входа в систему. Просто так, на всякий случай, если вы еще не догадались где следует искать следы активности взломщиков.
- /var/log/utmp — Список входов пользователей в систему на данный момент.
- /var/log/wtmp — Еще один журнал записи входа пользователей в систему. Вывод на экран командой
utmpdump
.
(5:535)$ sudo utmpdump /var/log/wtmp
[5] [02187] [l0 ] [ ] [4.0.5-gentoo ] [0.0.0.0 ] [Вт авг 11 16:50:07 2015]
[1] [00000] [~~ ] [shutdown] [4.0.5-gentoo ] [0.0.0.0 ] [Вт авг 11 16:50:08 2015]
[2] [00000] [~~ ] [reboot ] [3.18.12-gentoo ] [0.0.0.0 ] [Вт авг 11 16:50:57 2015]
[8] [00368] [rc ] [ ] [3.18.12-gentoo ] [0.0.0.0 ] [Вт авг 11 16:50:57 2015]
[1] [20019] [~~ ] [runlevel] [3.18.12-gentoo ] [0.0.0.0 ] [Вт авг 11 16:50:57 2015]
И другие журналы
Так как операционная система, даже такая замечательная как Linux, сама по себе никакой ощутимой пользы не несет в себе, то скорее всего на сервере или рабочей станции будет крутится база данных, веб сервер, разнообразные приложения. Каждое приложения или служба может иметь свой собственный файл или каталог журналов событий и ошибок. Всех их естественно невозможно перечислить, лишь некоторые.
- /var/log/mysql/ — Лог базы данных MySQL.
- /var/log/httpd/ или /var/log/apache2/ — Лог веб сервера Apache, журнал доступа находится в
access_log
, а ошибки — вerror_log
. - /var/log/lighthttpd/ — Лог веб сервера lighttpd.
В домашнем каталоге пользователя могут находится журналы графических приложений, DE.
- ~/.xsession-errors — Вывод
stderr
графических приложений X11.
Initializing "kcm_input" : "kcminit_mouse"
Initializing "kcm_access" : "kcminit_access"
Initializing "kcm_kgamma" : "kcminit_kgamma"
QXcbConnection: XCB error: 3 (BadWindow), sequence: 181, resource id: 10486050, major code: 20 (GetProperty), minor code: 0
kf5.kcoreaddons.kaboutdata: Could not initialize the equivalent properties of Q*Application: no instance (yet) existing.
QXcbConnection: XCB error: 3 (BadWindow), sequence: 181, resource id: 10486050, major code: 20 (GetProperty), minor code: 0
Qt: Session management error: networkIdsList argument is NULL
- ~/.xfce4-session.verbose-log — Сообщения рабочего стола XFCE4.
Чем просматривать — lnav
Почти все знают об утилите less
и команде tail -f
. Также для этих целей сгодится редактор vim
и файловый менеджер Midnight Commander. У всех есть свои недостатки: less
неважно обрабатывает журналы с длинными строками, принимая их за бинарники. Midnight Commander годится только для беглого просмотра, когда нет необходимости искать по сложному шаблону и переходить помногу взад и вперед между совпадениями. Редактор vim
понимает и подсвечивает синтаксис множества форматов, но если журнал часто обновляется, то появляются отвлекающие внимания сообщения об изменениях в файле. Впрочем это легко можно обойти с помощью <:view /path/to/file>
.
Недавно я обнаружил еще одну годную и многообещающую, но слегка еще сыроватую, утилиту — lnav, в расшифровке Log File Navigator.
Установка пакета как обычно одной командой.
$ aptitude install lnav #Debian/Ubuntu/LinuxMint
$ yum install lnav #RedHat/CentOS
$ dnf install lnav #Fedora
$ emerge -av lnav #Gentoo, нужно добавить в файл package.accept_keywords
$ yaourt -S lnav #Arch
Навигатор журналов lnav понимает ряд форматов файлов.
- Access_log веб сервера.
- CUPS page_log
- Syslog
- glog
- dpkg.log
- strace
- Произвольные записи с временными отметками
- gzip, bzip
- Журнал VMWare ESXi/vCenter
Что в данном случае означает понимание форматов файлов? Фокус в том, что lnav больше чем утилита для просмотра текстовых файлов. Программа умеет кое что еще. Можно открывать несколько файлов сразу и переключаться между ними.
(5:471)$ sudo lnav /var/log/pm-powersave.log /var/log/pm-suspend.log
Программа умеет напрямую открывать архивный файл.
(5:471)$ lnav -r /var/log/Xorg.0.log.old.gz
Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу <i>
. Это с моего syslog-а.
Mon May 02 20:25:00 123 normal 3 errors 0 warnings 0 marks
Mon May 02 22:40:00 2 normal 0 errors 0 warnings 0 marks
Mon May 02 23:25:00 10 normal 0 errors 0 warnings 0 marks
Tue May 03 07:25:00 96 normal 3 errors 0 warnings 0 marks
Tue May 03 23:50:00 10 normal 0 errors 0 warnings 0 marks
Wed May 04 07:40:00 96 normal 3 errors 0 warnings 0 marks
Wed May 04 08:30:00 2 normal 0 errors 0 warnings 0 marks
Wed May 04 10:40:00 10 normal 0 errors 0 warnings 0 marks
Wed May 04 11:50:00 126 normal 2 errors 1 warnings 0 marks
Кроме этого поддерживается подсветка синтаксиса, дополнение по табу и разные полезности в статусной строке. К недостаткам можно отнести нестабильность поведения и зависания. Надеюсь lnav будет активно развиваться, очень полезная программа на мой взгляд.
Использованные материалы
- lnav — An Advanced Log File viewer for Linux
- What Are Linux Logs? How to View Them, Most Important Directories, and More
- Как посмотреть логи в Linux
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!
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.