Отслеживание логов Linux в реальном времени. Система Syslog и журналы логов в Linux Логи линукса время работы программы

Системные администраторы, да и обычные пользователи 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 не вызовет у вас проблем. Если остались вопросы, задавайте в комментариях!

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

Managing Log files on a Linux System

Linux"s Log Files

All Linux systems generate systems logs that can be inspected to find information about your running system. These log files can contain a wealth of information from simple information messages to critical system issues. Most of the logging files that are created are in plain text. This means that it is very easy to view these using standard commands such as "more", "less", "cat", "head", "tail", "pg" or by using your preferred text editor such as "vi or vim".


By convention, most of the log files that are created are found under the directory "/var/log/". This is a standard area where system messages and logged/recorded. Depending on which Linux distribution you are using you will probably have a "message" file or a "syslog" file that contains recent activity. Logfiles are generally created by either a "syslogd" or "rsyslogd" logging demon. These demons are highly configurable and can filter messages into specified files. As well as handling local events, it is possible to log messages to remote servers dedicated to receiving these type of messages. It is quite common within larger organisations to have a dedicated syslog server. Some basic configuration options will be covered later. It is also common practice to have some form of log rotation process.

Below is a list of some of the more common log files that you will find. Some of these are distribution specific:


Log File Description
/var/log/messages Global system messages are logged here. (default logging area on some systems)
/var/log/syslog Global System messages are logged here. (default logging area on some systems)
/var/log/auth.log System Authorisation information, including user login information
/var/log/kern.log Kernel messages are logged here
/var/log/mail.log Contains logging information from your mail server
/var/log/boot.log System boot messages are logged here
/var/log/cups.log Printer related messages logged here
/var/log/wtmp Contains information relating to users logged onto your system
/var/log/samba Samba log files for smbd and nmbd. If configured can contain specific log files for users.
/var/log/dpkg.log Contains information from installations that use dpkg to install or remove a package
/var/log/zypper.log Contains messages from zypper package manager tool
/var/log/apt Contains information from package updates that use APT
/var/log/dmesg Contains Kernel ring buffer messages

Although the above is not an exhaustive view of all the files that can be found within the "/var/log" area. It does give you a rough idea of what is logged. It is important to remember that many third part products (software) will also write to this area. Often a sub-directory is created with various log information held within. Samba is a good example of this.

As mentioned earlier it is the "syslogd" or "rsyslogd" daemon that handles the majority of logging on your systems.

rsyslogd - logging utility

Rsyslogd is a reliable extended version of the syslogd service. Linux uses rsyslogd as its mechanism to record log files either in a central area or split into separate directories for clarity. It is also possible to send information to a dedicated logging server. Multiple processes may write to the same area without causing file locking. Simple commands can be used directly from scripts to write to this area.

Configuration Files

How rsyslogd behaves on your system is down to its configuration. This file is generally located in "/etc/rsyslog.conf". This file contains text which describes what should happen to messages when they are logged. It is here that you can specify specific directories for specific message types. Default logging rules are generally located under "/etc/rsyslog.d/"

Example of rsyslogd.conf under Ubuntu

/etc/rsyslog.conf


# Default logging rules can be found in /etc/rsyslog.d/50-default.conf ################# #### MODULES #### ################# $ModLoad imuxsock # provides support for local system logging $ModLoad imklog # provides kernel logging support (previously done by rklogd) #$ModLoad immark # provides --MARK-- message capability # provides UDP syslog reception #$ModLoad imudp #$UDPServerRun 514 # provides TCP syslog reception #$ModLoad imtcp #$InputTCPServerRun 514 ########################### #### 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 files # $WorkDirectory /var/spool/rsyslog # # Include all config files in /etc/rsyslog.d/ # $IncludeConfig /etc/rsyslog.d/*.conf

Hashes "#" are used to denote a comment or for commenting out a function that is not required.
Notice the last line $IncludeConfig /etc/rsyslog.d/*.conf . This is where we can specify custom rules/mappings.


# 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 # # Logging for the mail system. Split it up so that # it is easy to write scripts to parse these files. # #mail.info -/var/log/mail.info #mail.warn -/var/log/mail.warn mail.err /var/log/mail.err # # Logging for INN news system. # news.crit /var/log/news/news.crit news.err /var/log/news/news.err news.notice -/var/log/news/news.notice # # Some "catch-all" log files. # #*.=debug;\ # auth,authpriv.none;\ # news.none;mail.none -/var/log/debug #*.=info;*.=notice;*.=warn;\ # auth,authpriv.none;\ # cron,daemon.none;\ # mail,news.none -/var/log/messages # # Emergencies are sent to everybody logged in. # *.emerg:omusrmsg:* # # I like to have messages displayed on the console, but only on a virtual # console I usually leave idle. # #daemon,mail.*;\ # news.=crit;news.=err;news.=notice;\ # *.=debug;*.=info;\ # *.=notice;*.=warn /dev/tty8 # The named pipe /dev/xconsole is for the `xconsole" utility. To use it, # you must invoke `xconsole" with the `-file" option: # # $ xconsole -file /dev/xconsole [...] # # NOTE: adjust the list below, or you"ll go crazy if you have a reasonably # busy site.. # daemon.*;mail.*;\ news.err;\ *.=debug;*.=info;\ *.=notice;*.=warn |/dev/xconsole

The default logging area is called "syslog", see below exert


*.*;auth,authpriv.none -/var/log/syslog

What are Facilities and Levels?

Whenever the rsyslogd daemon receives a logging message, it acts based on the message type (Facility) and a Level (Priority). These mappings can be seen in your "/etc/syslog.conf" file or your included "/etc/syslog.d/*.conf" files.

Each entry within the configuration file can specify one or more facility/level selectors followed by an action. A selector consists of a facility or facilities followed by a single action. Action is normally the name of the directory and file that is to receive the messages into.

facility.level action

Example: mail.* -/var/log/mail - Here, "mail" is the facility, level is set to "*" and action is "/var/log/mail"

Facility

A facility represents the creator of the message, these normally consist of:

auth, authpriv, cron, daemon, kern, lpr, mail, mark, news, syslog, user, local0 - local7, "* " signifies any facility

These facilities give us the ability to control where messages from certain sources are sent to. The facilities local0 - local7 are for use by your own scripts.

Level (Priority)

The level specifies the severity threshold. These can be: (lowest priority first)

debug, info, notice, warning, err, crit, alert, emerg .

On older systems you may see "warn, error or panic". A level of none will disable the associated facility. These priorities control the amount of detail that is sent to each logfile. A single period "." separates the facility from the level. Together these are known as the message selector . An asterisk "* " may be used to specify all facilities or levels. Similar to facilities, wildcards "*" can be used along with "none". Only one level or wildcard may be specified with each selector. The following modifiers may be used "= " and "! "

If you specify only one level within a selector without any modifiers, you are actually specifying that level plus all other priorities. For example the selector user.notice is actually saying all user related messages having a level of notice or higher will be sent to the specified action area. If you require only a level of "notice", then you will have to use the "= " modifier:

user.=notice - Now means any user related messages with a level priority of "notice" only will be sent to the relevant logging area.

If you use the "! " modifier, this will negate your level priority. So if we specified user.!notice is the equivalent of all user related messages with a level priority of "notice" or higher. You can also specify user.!=notice which specify all user related messages except for ones with the level priority of "notice".

Actions

The action section is the destination for the messages. The action can be a filename such as "/var/log/syslog" or a hostname or IP address prefixed with the "@" sign. The latter option is popular in large organisations and enterprises. Quite often security related messages may be sent to a central logging server for further scrutiny.

rsyslog.conf structures

As rsyslogd is an enhanced version of the syslogd it can handle the older legacy style constructs known as sysklogd . It also handles legacy versions of rsyslog. However, the true power of rsyslog comes into play when you use what is known as "RainerScript ". This is the new style format for rsyslog which can handle complex cases with ease. In the example below you can see old format entries along with newer entries that use "if - then" constructs for a more precise handling.

Example section of "/etc/rsyslog.conf taken from openSUSE


# # NetworkManager into separate file and stop their further processing # if ($programname == "NetworkManager") or \ ($programname startswith "nm-") \ then -/var/log/NetworkManager & ~ # # email-messages # mail.* -/var/log/mail mail.info -/var/log/mail.info mail.warning -/var/log/mail.warn mail.err /var/log/mail.err # # news-messages # news.crit -/var/log/news/news.crit news.err -/var/log/news/news.err news.notice -/var/log/news/news.notice

Message Testing with the logger command

logger is a shell command interface into the syslog module. Logger allows you to make entries directly into the system log. This is very useful when incorporated into a script or when you want to test your message selector and mappings.

In its simplest form we can issue logger "I am a test" . This message would then go to our default area (probably /var/log/syslog or /var/log/messages) depending on how you have configured your rules. You can also specify a priority using the "-p or --priority" option. Examples of logger inaction:


john@john-desktop:/var/log$ logger "I am a Test of logger" Mar 22 22:39:51 john-desktop kernel: [ 9588.319477] dev_remove_pack: edad0884 not found. Mar 22 22:45:01 john-desktop CRON: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1) Mar 22 22:47:31 john-desktop john: I am a Test of logger

Basic Logger Usage

Usage: logger Options: -d, --udp use UDP (TCP is default) -i, --id log the process ID too -f, --file log the contents of this file -h, --help display this help text and exit -n, --server write to this remote syslog server -P, --port use this UDP port -p, --priority Mark given message with this priority -s, --stderr output message to standard error as well -t, --tag mark every line with this tag -u, --socket write to this Unix socket -V, --version output version information and exit

Getting help with Rsyslog

The above is intended as an overview to the processes that takes place for logging of messages to occur. For further information you can issue "man rsyslogd" from your console for an overview of the many options. For further reading you can head to the main "rsyslog" website: www.rsyslog.com

dmesg

"dmesg" is a special command that stands for display message. dmesg will display the message buffer of the kernel. dmesg is very useful if you want to view the messages that flew past your screen quickly during the boot process. Another useful trick is to redirect the output from the dmesg command to a temporary file: dmesg > /tmp/temp.txt .

dmesg is also useful if you are having issues with an I/O device or a "USB" device. dmesg can be used in combination with the grep command to find exactly what you are looking for quickly: dmesg | grep -i usb

dmesg basic Overview

Usage: dmesg Options: -C, --clear clear the kernel ring buffer -c, --read-clear read and clear all messages -D, --console-off disable printing messages to console -d, --show-delta show time delta between printed messages -E, --console-on enable printing messages to console -f, --facility restrict output to defined facilities -h, --help display this help and exit -k, --kernel display kernel messages -l, --level restrict output to defined levels -n, --console-level set level of messages printed to console -r, --raw print the raw message buffer -s, --buffer-size buffer size to query the kernel ring buffer -T, --ctime show human readable timestamp (could be inaccurate if you have used SUSPEND/RESUME) -t, --notime don"t print messages timestamp -u, --userspace display userspace messages -V, --version output version information and exit -x, --decode decode facility and level to readable string Supported log facilities: kern - kernel messages user - random user-level messages mail - mail system daemon - system daemons auth - security/authorisation messages syslog - messages generated internally by syslogd lpr - line printer subsystem news - network news subsystem Supported log levels (priorities): emerg - system is unusable alert - action must be taken immediately crit - critical conditions err - error conditions warn - warning conditions notice - normal but significant condition info - informational debug - debug-level messages

Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе 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 будет активно развиваться, очень полезная программа на мой взгляд.

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

Как устроена система регистрации событий?

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

Основным инструментом регистрации событий в UNIX и Linu до сих пор остаётся демон syslogd системы Syslog. Но следует иметь в виду также и то, что на протяжении длительного времени из-за многообразия всевозможных ответвлений UNIX и версий Linux множество программных пакетов, служебных скриптов, сетевых демонов используют свои собственные журналы, порой отличающимся экзотическим форматом.

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

Журналы регистрации легко просматривать, поскольку они являются обычными текстовыми файлами. Для эффективной работы с журналами используются самые стандартные инструменты из базовой поставки любого дистрибутива - команды и . Если нужно «ворошить» очень большие и сложные по формату журналы, то можно (и даже нужно) вместо утилиты grep использовать другой, гораздо более производительный и гибкий в подобных задачах инструмент - утилиту . Язык обработки текста Perl также очень хорошо подходит для этого.

Типичная запись системного журнала системы Syslog обычно выглядит следующим образом:

Dec 18 15:12:42 backup.main.superhosting.ru sbatchd: sbatchd/main: ls_info() failed: LIM is down; try later; trying ... Dec 18 15:14:28 system.main.superhosting.ru pop-proxy: Connection from 186.115.198.84 Dec 18 15:14:30 control.main.superhosting.ru pingem : office.main.superhosting.ru has not answered 42 times Dec 18 15:15:05 service.main.superhosting.ru vmunix: Multiple softerrors: Seen 100Corrected Softerrors from SIMM J0201 Dec 18 15:15:16 backup.main.superhosting.ru PAM_unix: (sshd) session closed "for user trent

В данном случае можно видеть, что в одном из журналов Syslog собраны события из нескольких источников: программы sbathd, pingem, pop-proxy. Также можно видеть, что события регистрируются для нескольких хостов, взаимодействующих с данной системой: backup, system, office и service.

log файлы и их расположение в Linux

Как уже отмечалось, в системах UNIX и Linux нет чётких соглашений о том, где и как должны храниться журналы регистрации. Они могут быть разбросаны хоть по всей файловой системе, поэтому для каждого администратора важно сразу разобраться, где и для каких пакетов и демонов находятся соответствующие файлы журналов. Но несмотря на отсутствие чётких формальных регламентов относительно мест хранения журналов, всё же существует традиционно сложившееся правило, что эти файлы должны находиться в каталогах /var/log, /var/log/syslog, а также в /var/adm.

Как правило, доступ для чтения файлов в указанных каталогах предоставляется только суперпользователю, однако нет ничего страшного, если для часто просматриваемых журналов, в которых также нет важной системной информации настроить более «демократический» режим доступа. Обычно к такому варианту также прибегают для удобства и экономии времени, когда нужно часто и регулярно изучать некоторые журналы, например для веб-сервера Apache, которые обычно находятся в /var/log/apache2 или /var/log/httpd.

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

Некоторые специальные файлы журналов

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

Файл Программа Место Частота Системы Назначение
acpid acpid Ф 64к RZ События, связанные с системой питания
auth.log sudo и прочие S М U Информация об авторизации
apache2/* httpd или apache2 Ф Д ZU Журналы веб-сервера Apache
apt* APT Ф М U Установщики пакетов
boot.log Сценарии запуска Ф М R Логи сценариев запуска
boot.msg Ядро В - Z Образ буфера сообщений ядра
cron, cron S Н RAH Логи и сведения о работе демона cron
cups/* CUPS Ф Н ZRU Сообщения, связанные с системой печати
daemon.log Разное S Н U Сообщения средств демонов
debug Разное S Д U Сообщения для отладки
dmesg Ядро В - RU Образ буфера сообщений ядра
dpkg.log dpkg Ф М U Установщики пакетов
faillog login Н Н RZU Информация о неудачных попытках авторизации
apache2/* Httpd или apache2 Ф Д R Журналы веб-сервера Apache для каталога /etc
kern.log login В - RZ Все сообщения средств ядра
lastlog login В - RZ Время последней регистрации в системе каждого пользователя (этот файл бинарный)
mail* Программы электронной почты S Н Все Сообщения средств электронной
messages Разное S Н RZUS
rpmpkgs cron.daily В Д R Список установленных RPM-пакетов
samba/* smbd и прочие Ф Н - Сведения о работе сервера Samba
secure sshd и прочие S М R Конфиденциальные авторизационные сообщения
sulog su Ф - SAH Сведения об удачных и неудачных попыток использования команды su
syslog* Разное S H SUH Основной системный журнальный файл
warn wpar S H Z События уровня системных предупреждений/ошибок
wpars/* wpar Ф - А Сведения о событиях загрузочных разделов
wtmp login В M Все Сообщения о регистрации в системе (бинарный файл)
xen/* Xen Ф 1m RZU Информация от монитора виртуальных машин Xen
Xorg.n.log Xorg Ф Н RS Сообщения об ошибках сервера X Windows
yum.log yum Ф М R Журнал управления пакетом

Для данной таблицы действуют следующие обозначения: S - Syslog, В - встроенное имя, Ф - конфигурационный файл, Д - ежедневно, Н - еженедельно, М - ежемесячно, NN - размер в килобайтах или мегабайтах, Z - SUSE, R - Red Hat и CentOS, S - Solaris, H - HP-UX, A - AIX. В столбце «Частота» указывается частота, с которой удаляется устаревшая информация, связанная со временем или с объёмом файла. В столбце «Программа» указывается программа, создающая файл.

Следует отметить также, что большая часть сообщений для представленных в таблице файлов направляется в систему Syslog. Уровень критичности и программа, создающая файл задаются в конфигурационном файле /etc/initlog.conf. - так работает система Syslog. Файл faillog является двоичным, и поэтому может быть прочтён утилитой failog.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter .



В продолжение темы:
Android

Веб-сервисы в 1СВ данной статье будет рассмотрены вопросы интеграции 1С с уже существующими веб-сервисами и использование самой 1С как веб-сервиса. При этом под веб-сервисами...