Время прочтения
6 мин
Просмотры 391K
Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе 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
Системные администраторы, да и обычные пользователи 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 не вызовет у вас проблем. Если остались вопросы, задавайте в комментариях!
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
I host about 200 websites and I have noticed that some got huge error_log files.
I would like to see which ones are consuming the most space so I can take a look on them and solve the error so they stop increasing in size so fast.
How can I find the biggest «error_log» files listed by location and size?
asked Jul 1, 2014 at 0:00
2
Have you tried something like this?
ls -lsR /var/log | sort -n | tail
Whether this works or not will depend on the structure of your log directories and the names of the files. This command will only tell you the file names of the ten largest files, not the directory paths.
Another option is something like this which finds all files over 1GB in size and prints the full paths to them:
find /var/log -size +1G -exec ls -lh {} +
Simply adjust the size to be slightly smaller than your largest log files.
Just in case you don’t know where these error_log
files are (judging by your other question, this might be the case), you can use locate error_log
or find / -name error_log
to find them. You can even add the -name error_log
parameter to the above find
command.
answered Jul 1, 2014 at 12:22
LadadadadaLadadadada
6714 silver badges8 bronze badges
You can see a listing of all files in a directory and deeper using the du
command.
An example of it’s usage would be
# du -h
46K ./R/win-library/3.0/colorspace/data
236K ./R/win-library/3.0/colorspace/doc
63K ./R/win-library/3.0/colorspace/help
12K ./R/win-library/3.0/colorspace/html
61K ./R/win-library/3.0/colorspace/libs/i386
57K ./R/win-library/3.0/colorspace/libs/x64
118K ./R/win-library/3.0/colorspace/libs
16K ./R/win-library/3.0/colorspace/Meta
# ....
answered Jul 1, 2014 at 1:22
rknuurknuu
111 bronze badge
I’m late to the party here but everyone missed this «I host about 200 websites..»
Your question indicates you are looking for error_log files which I take to mean the php error logs. Your best bet is to use find and depending on your system and where the web root directories are located it should look something like this
find . -type f -name "error_log" -ls | sort -nr -k7
If you find some really big error logs, it would be advisable to look at them since they are probably full of php warnings that are relatively easy to correct and this would reduce the file sizes dramatically. (source: web hosting system administrator)
answered Jul 15, 2015 at 16:37
rcjohnsonrcjohnson
8995 silver badges12 bronze badges
Try
find /var/log -type f -exec du -h {} + | sort -h | tail
to find the 10 largest files in /var/log and to display there size in human readable units. Leave out or modify the | tail
part to see more files.
Please note that the -h
flag is a GNU extensions of sort
and du
and may therefore not work on all systems. Due due rounding to human units, the result might be not in the correct ordering. Alternatively, you can use
find /var/log -type f -exec du {} + | sort -n | tail
It displays the file sizes in block sizes (usually 1024 or 512 bytes).
answered Jul 2, 2014 at 9:38
jofeljofel
26k6 gold badges65 silver badges90 bronze badges
2
Assuming that the error_log
files are located somewhere under /var/log
and that you are using the zsh
shell, the following command would list the pathnames of the 10 largest of those files:
printf '%sn' /var/log/**/error_log(.OL[1,10])
The glob qualifier (.OL[1,10])
will make sure that only regular files matches the pattern (.
) and that the results are sorted in decreasing order of size (OL
). The final [1,10]
requests the first ten results of the glob.
answered Aug 31, 2019 at 9:28
Kusalananda♦Kusalananda
307k35 gold badges598 silver badges896 bronze badges
What are Linux Log Files?
All Linux systems create and store information log files for boot processes, applications, and other events. These files can be a helpful resource for troubleshooting system issues.
Most Linux log files are stored in a plain ASCII text file and are in the /var/log directory and subdirectory. Logs are generated by the Linux system daemon log, syslogd or rsyslogd.
This tutorial will walk you through how to find and read Linux log files, and configure the system logging daemon.
Prerequisites
- Access to Linux
- A user account with root user privileges
1. First, open the Linux terminal as a root user. This will enable root privileges.
2. Use the following command to see the log files:
cd /var/log
3. To view the logs, type the following command:
ls
The command displays all Linux log files, such as kern.log and boot.log. These files contain the necessary information for the proper function of the operating system.
Log files are accessed using root privileges. By definition, root is the default account that has access to all Linux files.
Use the following example line command to access the respective file:
sudo less [log name here].log
This command displays a timeline of all information related to that operation.
Note that log files are stored in plain text so they can be viewed by using the following standard commands:
zcat
– Displays all the contents of logfile.gz
zmore
– See the file in pages, without decompressing the files
zgrep
– Search inside a compressed file
grep
– Find all occurrences of a search term in a file or filter a log file
tail
– Output the last few lines of files
head
– View the very beginning of text files
Note: Check out our comprehensive guide on grep to learn how to use it with examples.
Important Linux System Logs
Logs can tell a lot about the operations of a system. A good understanding of each type of file will help how to distinguish the respective logs.
Most directories can be grouped into one of four categories:
- System Logs
- Event Logs
- Application Logs
- Service Logs
Many of these logs can be located in the var/log subdirectory.
System Logs
Systems log files are needed for Linux to work. On its own, it contains the most significant amount of information about system functionality. The most common log files are:
/var/log/boot.log
: System Boot log (the boot log stores all information related to booting operations)/var/log/auth.log
: Auth logs (the authentication log stores all authentication logs, including successful and failed attempts)/var/log/httpd/
: Apache access and error logs/var/log/mysqld.log
: MySQL database server log file/var/log/debug
: Debug logs (the debug log stores detailed messages related to debugging and is useful for troubleshooting specific system operations)/var/log/daemon.log
: Daemon logs (the daemon log contains information about events related to running the Linux operation)/var/log/maillog
: Mail server logs (the mail log stores information related to mail servers and archiving emails)/var/log/kern.log
: Kernel logs (the kernel log stores information from the Ubuntu Linux kernel)/var/log/yum.log
: Yum command logs
System Logging Daemon
A daemon log is a program that runs in the background and is essential for system operations. These logs have their own category of logs and are seen as the heart of the logging operations for any system.
The path for the system login daemon’s configuration is /etc/syslog.conf
.
Each file consists of a selector and an action entry field. The syslogd
daemon can forward log messages as well. This can be useful for debugging purposes.
Application Logs
Application logs store information relevant to any application that is executed. This can include error messages, signs of system compromise, and browser identification string.
Log files that fall into this category include CUPS Print System logs, Rootkit Hunter log, Apache HTTP server logs, Samba SMB server logs, and X11 server log.
Non-Human-Readable Logs
Not all logs are designed in a human-readable format. Some are designed only to be read by system applications. Such files are often related to login information. They include login failure logs, last logins logs, and login records.
There are tools and software for reading Linux log files. They are not necessary for reading files as most can be read directly from the Linux terminal.
Supplemental GUIs for Viewing Linux Log Files
System Log Viewer is a GUI that can be used to monitor system logs.
The interface provides several functions for managing logs, including a log statistics display. It is a user-friendly log monitoring GUI.
Useful features include:
- A live view of logs
- Number of lines in the log
- Log size
- Most recent log dates
- Modifications made to logs
- Filters
- Keyboard Shortcuts
Alternatively, use Xlogmaster which can monitor a considerable number of log files. It features three different modes:
- Run mode: Starts a specified program and obtains stdout
- Cat mode: Cats files within specified intervals
- Tail mode: Checks log files within regular intervals
Xlogmaster is useful for increasing security. It translates all data for highlighting, hiding lines, and displays this information for taking user requested action.
How to Configure Log Files on Ubuntu and CentOS
This section explains different mechanisms for configuring log files. Let’s start with a CentOS example.
To view users currently logged onto a Linux server, enter the who command as a root user:
who
This also lists the login history of users. To view the login history of the system administrator, enter the following command:
last reboot
To view information of the last login, enter:
lastlog
Execute Log Rotation
Log files that have zeroes appended at the end are rotated files. That means log file names have automatically been changed within the system.
The purpose of log rotation is to compress outdated logs that are taking up space. Log rotation can be done using the logrotate
command. This command rotates, compresses, and mails system logs.
logrotate
handles systems that create significant amounts of log files. The command is used by the cron scheduler and reads the logrotate configuration file /etc/logrotate.conf
. It’s also used to read files in the logrotate configuration directory.
To include additional functionality to logrotate, start by entering the following command:
var/log/log name here].log {
Missingok
Notifempty
Compress
Size 20k
Daily
Create 0600 root root
}
It compresses and resizes the desired log file.
The commands perform the actions as follows:
missingok
– Tells logrotate
not to output an error if a log file is missing
notifempty
– Does not rotate the log file if it is empty. It reduces the size of the log file with gzip
size
– Ensures that the log file does not exceed the specified dimension and rotates it otherwise
daily
– Rotates the log files on a daily schedule. This can also be done on a weekly or monthly schedule
create
– Instantiates a log file where the owner and group are a root user
Conclusion
A thorough understanding of how to view and read Linux logs is necessary for troubleshooting a Linux system.
Using the proper commands and tools can simplify this process.
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:
Output
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:
Output
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:
Output
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:
Output
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:
Output
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:
Output
[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:
Output
# 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:
Output
-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:
Output
# 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:
Output
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:
Output
/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):
Output
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
How to Use Logrotate to Manage Log Files in Linux
Learn how to use the Logrotate utility in Linux-based systems to set up automatic compression and deletion of older log records
→
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.