- Landoflinux
- Managing Log files on a Linux System
- Linux Log Files and Locations
- rsyslogd — logging utility
- Configuration Files
- Example of rsyslogd.conf
- Default Rules for rsyslog
- What are Facilities and Levels?
- Facility
- Level (Priority)
- Actions
- rsyslog.conf structures
- Message Testing with the logger command
- Basic Logger Command Usage
- Getting help with rsyslog
- dmesg
- dmesg overview
- Лог файлы Linux по порядку
- Основные лог файлы
- И другие журналы
- Чем просматривать — lnav
Landoflinux
Managing Log files on a Linux System
Linux Log Files and Locations
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 organizations 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 party 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
Location: /etc/rsyslog.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
Below is an example of the default rules that can be found in the location: /etc/rsyslog.d/50-default.conf.
In the above example taken from a Linux Mint system, the default logging location is specified as «syslog«.
*.*;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 log file. 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 organizations 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 an openSUSE system
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 you 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. Below is an example of the «logger» command.
Basic Logger Command Usage
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/dmesg.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 overview
Below is the output from the dmesg —help command:
Источник
Лог файлы Linux по порядку
Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе Linux, который никогда не читал лог файлы. Операционная система и работающие приложения постоянно создают различные типы сообщений, которые регистрируются в различных файлах журналов. Умение определить нужный файл журнала и что искать в нем поможет существенно сэкономить время и быстрее устранить ошибку.
Журналирование является основным источником информации о работе системы и ее ошибках. В этом кратком руководстве рассмотрим основные аспекты журналирования операционной системы, структуру каталогов, программы для чтения и обзора логов.
Основные лог файлы
Все файлы журналов, можно отнести к одной из следующих категорий:
Большинство же лог файлов содержится в директории /var/log .
- /var/log/syslog или /var/log/messages содержит глобальный системный журнал, в котором пишутся сообщения с момента запуска системы, от ядра Linux, различных служб, обнаруженных устройствах, сетевых интерфейсов и много другого.
- /var/log/auth.log или /var/log/secure — информация об авторизации пользователей, включая удачные и неудачные попытки входа в систему, а также задействованные механизмы аутентификации.
- /var/log/dmesg — драйвера устройств. Одноименной командой можно просмотреть вывод содержимого файла. Размер журнала ограничен, когда файл достигнет своего предела, старые сообщения будут перезаписаны более новыми. Задав ключ —level= можно отфильтровать вывод по критерию значимости.
- /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 .
И другие журналы
Так как операционная система, даже такая замечательная как 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.
/.xfce4-session.verbose-log — Сообщения рабочего стола XFCE4.
Чем просматривать — lnav
Почти все знают об утилите less и команде tail -f . Также для этих целей сгодится редактор vim и файловый менеджер Midnight Commander. У всех есть свои недостатки: less неважно обрабатывает журналы с длинными строками, принимая их за бинарники. Midnight Commander годится только для беглого просмотра, когда нет необходимости искать по сложному шаблону и переходить помногу взад и вперед между совпадениями. Редактор vim понимает и подсвечивает синтаксис множества форматов, но если журнал часто обновляется, то появляются отвлекающие внимания сообщения об изменениях в файле. Впрочем это легко можно обойти с помощью .
Недавно я обнаружил еще одну годную и многообещающую, но слегка еще сыроватую, утилиту — lnav, в расшифровке Log File Navigator.
Установка пакета как обычно одной командой.
Навигатор журналов lnav понимает ряд форматов файлов.
- Access_log веб сервера.
- CUPS page_log
- Syslog
- glog
- dpkg.log
- strace
- Произвольные записи с временными отметками
- gzip, bzip
- Журнал VMWare ESXi/vCenter
Что в данном случае означает понимание форматов файлов? Фокус в том, что lnav больше чем утилита для просмотра текстовых файлов. Программа умеет кое что еще. Можно открывать несколько файлов сразу и переключаться между ними.
Программа умеет напрямую открывать архивный файл.
Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу . Это с моего syslog-а.
Кроме этого поддерживается подсветка синтаксиса, дополнение по табу и разные полезности в статусной строке. К недостаткам можно отнести нестабильность поведения и зависания. Надеюсь lnav будет активно развиваться, очень полезная программа на мой взгляд.
Источник