Лог файлы 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 будет активно развиваться, очень полезная программа на мой взгляд.
Источник
LInux kernel log
I’m running embedded Linux (Angstrom distribution, for Atmel). I would like to read the kernel message log during shutdown, same stuff I’d get with dmesg. Basically I’m exploring a few issues I have by inserting printk() in the kernel code and now I’d like to see their output.
I found logs aren’t automatically started when the system powers up (how can I?) and I cannot obtain anything with klogd command.
3 Answers 3
If klogd is started too late or stopped too early for you to see your messages, maybe you could give a try to Netconsole ?
If you have a network access to your embedded board, of course. This module is easy to configure and I’ve used it successfully a couple of times in the past. Note that if you want to be able to see messages emited very early/late in the boot process, you will have to compile it inside the kernel (with your Ethernet driver), not as a module.
Also, check your default log level allows your printk() to be displayed (loglevel= kernel boot parameter)
The trusty RS232 serial console is probably your friend in circumstances like these.
Unless you’ve taken steps to disable it, kernel log messages will almost certainly be finding their way there.
Different distro may redirect the output of /proc/kmsg to any physical log files or virtual devices (/dev/xxx) they like. But «/proc/kmsg» is the original ultimate source of the kernel log, as the kernel actually implement its ring buffer operation inside fs/proc/kmsg.c:
And here is more info:
So how you see the output is this:
sudo tail -f /proc/kmsg
And you can only see all the messages generated AFTER you have issued this command — all previous messages in the ring buffer will not be printed out. And so to see the physical file output, you can search for the user of «/proc/kmsg»:
sudo lsof |grep proc.kmsg
And my machine indicated this:
So now it is pid 1743, let’s see the files fd opened by 1743:
Источник
Message logging with printkВ¶
printk() is one of the most widely known functions in the Linux kernel. It’s the standard tool we have for printing messages and usually the most basic way of tracing and debugging. If you’re familiar with printf(3) you can tell printk() is based on it, although it has some functional differences:
printk() messages can specify a log level.
the format string, while largely compatible with C99, doesn’t follow the exact same specification. It has some extensions and a few limitations (no %n or floating point conversion specifiers). See How to get printk format specifiers right .
All printk() messages are printed to the kernel log buffer, which is a ring buffer exported to userspace through /dev/kmsg. The usual way to read it is using dmesg .
printk() is typically used like this:
where KERN_INFO is the log level (note that it’s concatenated to the format string, the log level is not a separate argument). The available log levels are:
pr_debug() and pr_devel() if DEBUG is defined
The log level specifies the importance of a message. The kernel decides whether to show the message immediately (printing it to the current console) depending on its log level and the current console_loglevel (a kernel variable). If the message priority is higher (lower log level value) than the console_loglevel the message will be printed to the console.
If the log level is omitted, the message is printed with KERN_DEFAULT level.
You can check the current console_loglevel with:
The result shows the current, default, minimum and boot-time-default log levels.
To change the current console_loglevel simply write the desired level to /proc/sys/kernel/printk . For example, to print all messages to the console:
Another way, using dmesg :
sets the console_loglevel to print KERN_WARNING (4) or more severe messages to console. See dmesg(1) for more information.
As an alternative to printk() you can use the pr_*() aliases for logging. This family of macros embed the log level in the macro names. For example:
prints a KERN_INFO message.
Besides being more concise than the equivalent printk() calls, they can use a common definition for the format string through the pr_fmt() macro. For instance, defining this at the top of a source file (before any #include directive):
would prefix every pr_*() message in that file with the module and function name that originated the message.
For debugging purposes there are also two conditionally-compiled macros: pr_debug() and pr_devel() , which are compiled-out unless DEBUG (or also CONFIG_DYNAMIC_DEBUG in the case of pr_debug() ) is defined.
Function referenceВ¶
used by the pr_*() macros to generate the printk format string
Parameters
format string passed from a pr_*() macro
Description
This macro can be used to generate a unified format string for pr_*() macros. A common use is to prefix all pr_*() messages in a file with a common string. For example, defining this at the top of a source file:
#define pr_fmt(fmt) KBUILD_MODNAME “: ” fmt
would prefix all pr_info, pr_emerg… messages in the file with the module name.
print a kernel message
Parameters
Description
This is printk() . It can be called from any context. We want it to work.
If printk indexing is enabled, _printk() is called from printk_index_wrap. Otherwise, printk is simply #defined to _printk.
We try to grab the console_lock. If we succeed, it’s easy — we log the output and call the console drivers. If we fail to get the semaphore, we place the output into the log buffer and return. The current holder of the console_sem will notice the new output in console_unlock() ; and will send it to the consoles before releasing the lock.
One effect of this deferred printing is that code which calls printk() and then changes console_loglevel may break. This is because console_loglevel is inspected when the actual printing occurs.
See also: printf(3)
See the vsnprintf() documentation for format string extensions over C99.
Print an emergency-level message
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_EMERG loglevel. It uses pr_fmt() to generate the format string.
Print an alert-level message
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_ALERT loglevel. It uses pr_fmt() to generate the format string.
Print a critical-level message
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_CRIT loglevel. It uses pr_fmt() to generate the format string.
Print an error-level message
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_ERR loglevel. It uses pr_fmt() to generate the format string.
Print a warning-level message
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_WARNING loglevel. It uses pr_fmt() to generate the format string.
Print a notice-level message
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_NOTICE loglevel. It uses pr_fmt() to generate the format string.
Print an info-level message
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_INFO loglevel. It uses pr_fmt() to generate the format string.
Continues a previous log message in the same line.
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_CONT loglevel. It should only be used when continuing a log message with no newline (вЂn’) enclosed. Otherwise it defaults back to KERN_DEFAULT loglevel.
Print a debug-level message conditionally
Parameters
arguments for the format string
Description
This macro expands to a printk with KERN_DEBUG loglevel if DEBUG is defined. Otherwise it does nothing.
It uses pr_fmt() to generate the format string.
Print a debug-level message conditionally
Parameters
arguments for the format string
Description
This macro expands to dynamic_pr_debug() if CONFIG_DYNAMIC_DEBUG is set. Otherwise, if DEBUG is defined, it’s equivalent to a printk with KERN_DEBUG loglevel. If DEBUG is not defined it does nothing.
It uses pr_fmt() to generate the format string (dynamic_pr_debug() uses pr_fmt() internally).
© Copyright The kernel development community.
Источник