Linux log file приложения. Системные журналы Linux (управление логированием)

Introduction

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

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

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

Target Audience

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

System Logs

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

Authorization Log

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

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

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

Daemon Log

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

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

Debug Log

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

Kernel Log

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

Kernel Ring Buffer

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

dmesg | less

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

dmesg | grep pnp | less

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

System Log

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

Application Logs

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

Apache HTTP Server Logs

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

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

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

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

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

CUPS Print System Logs

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

Rootkit Hunter Log

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

Samba SMB Server Logs

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

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

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

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

X11 Server Log

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

Non-Human-Readable Logs

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

Login Failures Log

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

faillog

Last Logins Log

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

lastlog | less

Login Records Log

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

who

System Logging Daemon (syslogd)

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

Configuration of syslogd

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

Echoing Messages to syslogd With Logger

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

logger This Pizza from Vinnys Gourmet Rocks

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

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

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

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

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

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

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

Log Rotation

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

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

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

Essential Commands

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

Getting Started

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

cd /var/log

Editing Files

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

nano example.log

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

Viewing Files

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

less example.log

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

Viewing the Beginning of Files

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

head example.log

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

head -n 20 example.log

Viewing the End of Files

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

tail example.log

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

tail -n 20 example.log

Watching a Changing File

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

tail -f example.log

Press Ctrl+C to quit the loop.

Searching Files

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

grep "system" example.log

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

grep "^system" example.log

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

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

grep "system" example.log | less

Resources

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

Local System Resources

System manual page for the dmesg kernel ring buffer utility

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

System manual page for the grep pattern searching utility

System manual page for the head utility

System manual page for the kernel log daemon (klogd)

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

System manual page for the less paging utility

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

System manual page for the the logrotate utility

System manual page for the savelog log file saving utility

System manual page for the system log daemon (syslogd)

System manual page for the syslogd configuration file

System manual page for the tail utility

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

Узнайте о файлах журналов, когда ваша система работает гладко, как это понимание лог-файлов поможет вам успешно диагностировать и устранить любые проблемы, которые могут возникнуть в дальнейшем.

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

Общие файлы журнала

В качестве общего стандарта в почти каждой системе Linux, файлы журналов находятся в каталоге /var/log . Любые другие приложения, которые вы можете позже установить на вашей системе, вероятно, бросят свои файлы журнала здесь. После входа в вашу систему, наберите команду

Ls -l /var/log

Чтобы просмотреть содержимое этого каталога.

/var/log/messages – Большая часть общих системных сообщений регистрируются здесь, включая сообщения во время запуска системы.
/var/log/cron – Сообщения демона cron регистрируются здесь. Создается и останавливаются задачи, а также сообщения об ошибках.
/var/log/maillog или /var/log/mail.log – Регистрация информации почтового сервера, запущенного на сервере.
/var/log/wtmp – Содержит историю всех входов и выходов.
/var/log/btmp – Записи неудачных попыток входа в систему.
/var/run/utmp – Логирование настоящего входа в состояние каждого пользователя.
/var/log/dmesg – Содержит очень важные сообщения о ядре кольцевого буфера. В человеческом понимании это означает, что, когда ядро раскручивается он записывает всю информацию здесь. Команда dmesg может быть использована для просмотра сообщений этого файла.
/var/log/secure – Сообщения, связанные с безопасностью будут храниться здесь. Это включает в себя сообщения от SSH – демона, неудачный ввод пароля, несуществующих пользователей и т.д.
/var/log/mariadb – Если MariaDB установлена в системе, то это место, где она будет бросать журналы по умолчанию
/var/log/mysql – Если база данных устанавливается, то это директория записи данных по умолчанию.

Просмотр и управление файлами журналов

Первичная регистрация Linux демона процесс rsyslogd и его конфигурация находится в /etc/rsyslog.conf .

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

Для просмотра последних 500 записей файла введите следующую команду:

Tail -n 500 /var/log/messages

Для мониторинга журналов в режиме реального времени tail -f также очень полезная команда, которая будет отслеживать сообщения, как они вошли. Это особенно полезно при поиске и устранении потоков почты и ошибки доставки почты.

Tail -f /var/log/maillog

Некоторые журналы Linux, как бинарные файлы, которые должны быть разобраны другим приложением, специально адаптированный для просмотра этих журналов. Эти журналы сохраняются в /var/log/wtmp /var/log/btmp и /var/run/utmp .

Для просмотра содержимого /var/log/wtmp используется: last
Для просмотра содержимого /var/log/btmp используется: lastb
Для просмотра содержимого /var/run/utmp используется: who

Cpanel файлы конкретных журналов

Файлы журнала Apache:

/usr/local/apache/logs/ – Общие журналы .
/usr/local/apache/domlogs/ – Журналы конкретного домена.

файлы журнала Exim:

/var/log/exim_mainlog
/var/log/exim_rejectlog

Файлы журнала Cpanel:

/usr/local/cpanel/logs/ – Все связанные с Cpanel сообщений в этом месте.

Файлы конкретных журналов DirectAdmin

Файлы журнала DirectAdmin

/var/log/directadmin/ – DirectAdmin связанные журналы.

Файлы журналов

/var/log/httpd/ – Веб-сервер Apache вошли в стандартный каталог.
/var/log/httpd/domains/ – Для всех остальных доменов журналы находятся в этом подкаталоге.

Файлы журнала

/var/log/proftpd/ – Если используется ProFTPd.
/var/log/pureftpd.log – Если используется PureFTPd.

Файлы журналов Exim

/var/log/exim/ – Журналы агента пересылки почты Exim в этой директории.

Файлы журналов

/var/lib/mysql/server.hostname.com.err – Это каталог, ведение журнала на наличие ошибок, связанных с .

Файлы журналов

/var/log/yum.log – Логирование менеджера пакетов Yum.
/var/log/httpd – В системах, основанных на / RedHat CentOS это где веб-сервер Apache будет хранить журналы по умолчанию.

Файлы журналов

/var/log/apache2/ – На системах Ubuntu журналы веб-сервера Apache хранятся в этом каталоге.
/var/log/apt/ – Журналы из управления пакетами в Ubuntu.

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

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

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

Большинство файлов логов Linux находятся в папке /var/log/ Вы можете список файлов логов для вашей системы с помощью команды ls:

Rw-r--r-- 1 root root 52198 май 10 11:03 alternatives.log
drwxr-x--- 2 root root 4096 ноя 14 15:07 apache2
drwxr-xr-x 2 root root 4096 апр 25 12:31 apparmor
drwx------ 2 root root 4096 май 5 10:15 audit
-rw-r--r-- 1 root root 33100 май 10 10:33 boot.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. Это может быть любой текстовый редактор, или специальная утилита. Скорее всего, вам понадобятся права суперпользователя для того чтобы посмотреть логи в Linux. Вот команды, которые чаще всего используются для этих целей:

  • zgrep
  • zmore

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

Смотрим лог /var/log/messages, с возможностью прокрутки:

less /var/log/messages

Просмотр логов Linux, в реальном времени:

tail -f /var/log/messages

Открываем лог файл dmesg:

cat /var/log/dmesg

Первые строки dmesg:

head /var/log/dmesg

Выводим только ошибки из /var/log/messages:

grep -i error /var/log/messages

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

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

Выводы

В каталоге /var/log вы можете найти всю необходимую информацию о работе Linux. Из сегодняшней статьи вы достаточно узнали, чтобы знать где искать, и что искать. Теперь просмотр логов в Linux не вызовет у вас проблем. Если остались вопросы, задавайте в комментариях!



Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе 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 usb 1-1.1: 2:1: cannot get freq at ep 0x1 usb 1-1.1: 1:1: cannot get freq at ep 0x81 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 [Вт авг 11 16:50:07 2015] [~~ ] [Вт авг 11 16:50:08 2015] [~~ ] [Вт авг 11 16:50:57 2015] [Вт авг 11 16:50:57 2015] [~~ ] [Вт авг 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
  • 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

Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу . Это с моего 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 будет активно развиваться, очень полезная программа на мой взгляд.

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

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

Viewing System Logs on Ubuntu

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

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

View Log Files Through Gnome Logs

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

Type Logs in the Ubuntu dash:

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

Click on the System tab to view system logs:

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

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

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

Through Log File Viewer

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

In order to access the Log File Viewer:

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

The Log File Viewer will appear as follows:


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

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

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

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

View Log Files Through the Terminal

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

Open the Terminal and enter the following command:

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

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

Customizing dmesg output

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

$ dmesg |less

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

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

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

$ dmesg |grep core

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

Open a Log File with cat Command

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

$ cat

$ cat /var/log/syslog

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

$ cat |grep

$ cat |less

Writing To the System Log

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

Open the Ubuntu Terminal and type the following command:

$ logger “This is a custom message”


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

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

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

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

How to View System Log Files on Ubuntu 18.04 LTS