- Лог файлы Linux по порядку
- Основные лог файлы
- И другие журналы
- Чем просматривать — lnav
- How to View & Read Linux Log Files
- What are Linux Log Files?
- How to View Linux Logs
- Important Linux System Logs
- System Logs
- System Logging Daemon
- Application Logs
- Non-Human-Readable Logs
- Supplemental GUIs for Viewing Linux Log Files
- How to Configure Log Files on Ubuntu and CentOS
- Execute Log Rotation
Лог файлы 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 будет активно развиваться, очень полезная программа на мой взгляд.
Источник
How to View & Read Linux Log Files
Home » SysAdmin » How to View & Read Linux Log Files
What are Linux Log Files?
All Linux systems create and store information log files for boot processes, applications, and other events. These files can be a helpful resource for troubleshooting system issues.
Most Linux log files are stored in a plain ASCII text file and are in the /var/log directory and subdirectory. Logs are generated by the Linux system daemon log, syslogd or rsyslogd.
This tutorial will walk you through how to find and read Linux log files, and configure the system logging daemon.
- Access to Linux
- A user account with root user privileges
How to View Linux Logs
1. First, open the Linux terminal as a root user. This will enable root privileges.
2. Use the following command to see the log files:
3. To view the logs, type the following command:
The command displays all Linux log files, such as kern.log and boot.log. These files contain the necessary information for the proper function of the operating system.
Log files are accessed using root privileges. By definition, root is the default account that has access to all Linux files.
Use the following example line command to access the respective file:
This command displays a timeline of all information related to that operation.
Note that log files are stored in plain text so they can be viewed by using the following standard commands:
zcat – Displays all the contents of logfile.gz
zmore – See the file in pages, without decompressing the files
zgrep – Search inside a compressed file
grep – Find all occurrences of a search term in a file or filter a log file
tail – Output the last few lines of files
head – View the very beginning of text files
Note: Check out our comprehensive guide on grep to learn how to use it with examples.
Important Linux System Logs
Logs can tell a lot about the operations of a system. A good understanding of each type of file will help how to distinguish the respective logs.
Most directories can be grouped into one of four categories:
Many of these logs can be located in the var/log subdirectory.
System Logs
Systems log files are needed for Linux to work. On its own, it contains the most significant amount of information about system functionality. The most common log files are:
- /var/log/boot.log : System Boot log (the boot log stores all information related to booting operations)
- /var/log/auth.log : Auth logs (the authentication log stores all authentication logs, including successful and failed attempts)
- /var/log/httpd/ : Apache access and error logs
- /var/log/mysqld.log : MySQL database server log file
- /var/log/debug : Debug logs (the debug log stores detailed messages related to debugging and is useful for troubleshooting specific system operations)
- /var/log/daemon.log : Daemon logs (the daemon log contains information about events related to running the Linux operation)
- /var/log/maillog : Mail server logs (the mail log stores information related to mail servers and archiving emails)
- /var/log/kern.log : Kernel logs (the kernel log stores information from the Ubuntu Linux kernel)
- /var/log/yum.log : Yum command logs
System Logging Daemon
A daemon log is a program that runs in the background and is essential for system operations. These logs have their own category of logs and are seen as the heart of the logging operations for any system.
The path for the system login daemon’s configuration is /etc/syslog.conf .
Each file consists of a selector and an action entry field. The syslogd daemon can forward log messages as well. This can be useful for debugging purposes.
Application Logs
Application logs store information relevant to any application that is executed. This can include error messages, signs of system compromise, and browser identification string.
Log files that fall into this category include CUPS Print System logs, Rootkit Hunter log, Apache HTTP server logs, Samba SMB server logs, and X11 server log.
Non-Human-Readable Logs
Not all logs are designed in a human-readable format. Some are designed only to be read by system applications. Such files are often related to login information. They include login failure logs, last logins logs, and login records.
There are tools and software for reading Linux log files. They are not necessary for reading files as most can be read directly from the Linux terminal.
Supplemental GUIs for Viewing Linux Log Files
System Log Viewer is a GUI that can be used to monitor system logs.
The interface provides several functions for managing logs, including a log statistics display. It is a user-friendly log monitoring GUI.
Useful features include:
- A live view of logs
- Number of lines in the log
- Log size
- Most recent log dates
- Modifications made to logs
- Filters
- Keyboard Shortcuts
Alternatively, use Xlogmaster which can monitor a considerable number of log files. It features three different modes:
- Run mode: Starts a specified program and obtains stdout
- Cat mode: Cats files within specified intervals
- Tail mode: Checks log files within regular intervals
Xlogmaster is useful for increasing security. It translates all data for highlighting, hiding lines, and displays this information for taking user requested action.
How to Configure Log Files on Ubuntu and CentOS
This section explains different mechanisms for configuring log files. Let’s start with a CentOS example.
To view users currently logged onto a Linux server, enter the who command as a root user:
This also lists the login history of users. To view the login history of the system administrator, enter the following command:
To view information of the last login, enter:
Execute Log Rotation
Log files that have zeroes appended at the end are rotated files. That means log file names have automatically been changed within the system.
The purpose of log rotation is to compress outdated logs that are taking up space. Log rotation can be done using the logrotate command. This command rotates, compresses, and mails system logs.
logrotate handles systems that create significant amounts of log files. The command is used by the cron scheduler and reads the logrotate configuration file /etc/logrotate.conf . It’s also used to read files in the logrotate configuration directory.
To include additional functionality to logrotate, start by entering the following command:
It compresses and resizes the desired log file.
The commands perform the actions as follows:
missingok – Tells logrotate not to output an error if a log file is missing
notifempty – Does not rotate the log file if it is empty. It reduces the size of the log file with gzip
size – Ensures that the log file does not exceed the specified dimension and rotates it otherwise
daily – Rotates the log files on a daily schedule. This can also be done on a weekly or monthly schedule
create – Instantiates a log file where the owner and group are a root user
A thorough understanding of how to view and read Linux logs is necessary for troubleshooting a Linux system.
Using the proper commands and tools can simplify this process.
Источник