Linux log all output

Лог файлы 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
Читайте также:  Лучший домашний медиа сервер для windows

Что в данном случае означает понимание форматов файлов? Фокус в том, что lnav больше чем утилита для просмотра текстовых файлов. Программа умеет кое что еще. Можно открывать несколько файлов сразу и переключаться между ними.

Программа умеет напрямую открывать архивный файл.

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

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

Источник

Как посмотреть логи в Linux

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

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

Расположение логов по умолчанию

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

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

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

Читайте также:  Warcraft iii the frozen throne для mac os

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

Источник

How To View And Configure Linux Logs On Ubuntu 20.04

By Juraj Holub
Last Validated on April 30 2021 · Originally Published on April 30, 2021 · Viewed 1.1k times

Introduction

This tutorial explains the administration of the Linux system logs. A system log is a file that contains information about events that happened on the system during runtime. After reading this tutorial you will be confident in the following Linux logging basics:

  • Where are the Linux log files stored, how are they formatted, and how to read them.
  • How to read the most important logs including syslog.
  • How to view Ubuntu syslog daemon configuration.
  • How to configure Linux rotation log files, and execute log rotation.

Prerequisites

  • Basic knowledge of how to work with Linux command line.
  • Ubuntu 20.04 distribution including the non-root user with sudo access.

Step 1 — Finding Linux System Logs

The Ubuntu system stores all system logs into directory /var/log . Let’s look at the most essential log files, their meaning, and what they store:

  • /var/log/syslog stores all records about any global activity in the system. Basically, every event that happens goes into this log.
  • /var/log/auth.log stores all security-related actions. Those include login, logout, and root user activity.
  • /var/log/kern.log stores events of the kernel like info, warning, and errors. Those logs are especially useful for custom kernels.
  • /var/log/boot.log stores system startup info.

The /var/log directory also contains various application logs. For example, if your distribution contains Apache or MySQL then their logs are also stored there.

You can view content of this directory with the following command:

The ls utility list contents of the /var/log directory into your terminal:

The output shows that there is a lot of various log files with several different suffixes. We will examine their meaning later in the tutorial. For now you should recognize files syslog , auth.log , boot.log and kern.log because we already know them. These system logs that are on every Ubuntu distribution.

Since the command was executed on Ubuntu with installed Apache application, you can see that there is also a directory called apache2 which holds log files for this application.

Step 2 — Viewing Log File Contents

The log files contain a large amount of various information that can be helpful for analysing activities like finding vulnerabilities, system optimisation, monitoring of the system, network, or server, and others.

The log files content must be formatted in a well-known structure for portability reasons. Let’s review the two basic log file formats: plain text and binary.

Plaintext Log Files

These logs are plain text files with the standardized content format. Ubuntu uses the log template called RSYSLOG_TraditionalFileFormat (see templates documentation). This log format consists of four main fields with a space delimiter:

  1. Timestamp: Indicates the time formatted as MMM dd HH:mm:ss (e.g. Sep 28 19:00:00 ). Note that this format does not include a year.
  2. Hostname: Is the name of the host or system that originally created the message.
  3. Application: Is the name of the application that created the message.
  4. Message: Contains the information. It can also be formatted.

Now, let’s review some log file with this format. Print the contents of file /var/log/syslog with utility tail :

The command prints the last 10 lines of this log file:

The output shows that records of this file are formatted as described earlier. For example, the last record contains timestamp Mar 23 12:39:23 , hostname peter , application systemd[1] and message Finished Clean php session files .

Binary Log Files

Those are another type of log files that cannot be read with a regular text editor. The directory /var/log contains multiple binary files that are related to users authorization:

  • /var/log/utmp stores users currently logged in the system.
  • /var/log/wtmp stores users previously logged in. It contains the past data from utmp .
  • /var/log/btmp stores failed login attempts.

For these binary logs, the system offers a special command-line tools that show you the relevant information in human-readable form.

To review the /var/log/utmp , run the utility who with option -H (this option shows output as a table and includes column names):

You’ll see the program’s output appear on the screen:

The output shows system users that are currently logged in as well as their timestamp and IP address.

To review the /var/log/wtmp , run the utility last with option -R (this option will suppress the hostname column that is not important for us):

You’ll see the program’s output appear on the screen:

The output shows a table where the first column refers to the user name (the pseudo-user reboot is recorded each time when the system is rebooted). The third field refers to the login timestamp, and the last column shows the entire session duration.

To review the /var/log/btmp , run the utility lastb with a sudo privilege:

You’ll see the program’s output appear on the screen:

The output shows users that failed to login with the corresponding timestamp.

Step 3 — Viewing Syslog Deamon Configuration

All logs are created and maintained by a background program called daemon. The traditional Linux daemon for logging is syslogd . However, Ubuntu 20.04 distribution uses a daemon called rsyslogd . Rsyslogd means rocket-fast system for log processing, and it is a superset of basic syslogd. This daemon uses a special configuration file /etc/rsyslog.conf that specifies the logging rules.

Читайте также:  Как сделать свою персонализацию для windows 10

Print the content of file /etc/rsyslog.conf with utility cat :

The command prints entire content of the configuration file:

The output shows a lot of information, but we focus on two configuration details. Firstly, there is a variable $ActionFileDefaultTemplate that defines syslog record format, and we already know this format from Step 2. We can change this variable if this format is not suitable for us.

Secondly, the output contains a special variable $IncludeConfig that specifies the directory for all configuration files.

On Ubuntu, all rsyslog rules are by default in the /etc/rsyslog.d/50-default.conf file. Print the content of this file with the utility head (option -n 15 specifies to print first 15 lines of a given file):

You’ll see the program’s output appear on the screen:

The output contains the rsyslogd configuration rules. Each non-empty line (or line that does not start with char # ) defines a rule. The rule definition starts with a selector followed by one or more spaces and an action field:

  • The selector specifies the facility with corresponding priority. For example, in our output, the * refers to all facilities or all priorities.
  • The action usually refers to a log file. For example, in our output, the selector * refers to the /var/log/syslog file that we already know.

Step 4 — Viewing Rotating Log Files

The size of log files must be controlled because it keeps growing over time. Each system has limited resources, and too large logs lead to performance and memory problems. Linux solves this problem with a concept called rotating logs. Rotation continuously repeats the following actions:

  1. Instead of deleting the log file, Linux changes the file name to a name with a version suffix and creates a new one. The log file has multiple old back-ups. Optionally, these backups are compressed.
  2. When the count of backup files reaches a specified number, the system deletes the oldest.

Let’s view an example of Linux rotating files. Execute ls command with following options:

The -l option formats the output in a long listing including various metadata. The -h option prints file in a human-readable form, and the -t option sorts the output listing by modification time (newest first). The parameter /var/log/syslog* specifies to view all files at directory /var/log that starts with prefix syslog .

You’ll see the program’s output appear on the screen:

The output shows all version of syslog . Typically, it is the biggest log file because as explained earlier, this log stores basically every event of the system. The older versions are labelled with version suffix (e.g. syslog.6.gz is the oldest syslog backup).

You can see that the backups are compressed (the gz suffix means that the file is compressed by the standard GNU zip compression algorithm). As you can observe, these files grow to the size of gigabytes (in our example the biggest is 3.5 GB large). At last, you can view that these files cover only a time interval of six days.

Step 5 — Running Logrotate Daemon

The log rotation is maintained by the system daemon logrotate . Similarly to rsyslogd , the daemon uses a special configuration file /etc/logrotate.conf .

Print the content of file /etc/logrotate.conf with utility cat :

The command prints the entire content of this configuration file:

The output shows the global configuration. The contents are quite self-explaining. In our example, the log files are rotated weekly, and the system keeps four rotation backlogs, and the compression is turned off. However, this is the most general configuration for any log, and we can set up a more specific configuration for a specific log.

In Ubuntu, the specific logs are by default configured in directory /etc/logrotate.d (you can see that this directory is included in logrotate.conf ).

Let’s view content of /etc/logrotate.d by executing ls :

The command lists all files into output:

You can see that rsyslog daemon contains its own logrotate configuration file.

Print first 15 lines of rsyslog configuration file with utility head :

You’ll see the program’s output appear on the screen:

The output shows that syslog file is rotated daily, keeps seven backups, and backups are compressed.

You can force logrotate to execute rotation immediately by following command ( sudo access required):

The option f force immediate rotation, and the option v turns on verbose mode (it will display messages during rotation). The execution of this command shows the following output:

The beginning of the output shows that logrotate daemon firstly reads all configuration files. The entire output is very long because it informs about every detail of the rotation progress.

Conclusion

In this tutorial, you viewed the most important Linux logs with examples on syslog. You explored the structure of plain text log files, binary log file, and you opened and checked system configuration for daemon rsyslogd that maintains logs on Ubuntu. Apart from that you also saw a configuration of the logrotate daemon, and you executed log rotation.

Источник

Оцените статью