See user log linux

How to View and Configure Linux System Logs on Ubuntu 20.04

This tutorial explains the basic administration of a Linux server through system logs. A system log is a file that contains information about the events that happened on the system during runtime.

In this article, you will learn the following Linux logging basics:

  • Where the Linux log files are stored, how are they formatted, and how to read them.
  • How to read the most important logs (such as syslog ).
  • How to configure the Ubuntu syslog daemon.
  • What Linux log rotation is all about and how to use the logrotate utility.

Prerequisites

Before proceeding with the rest of this tutorial, ensure that you have a basic knowledge of working with the Linux command line. While many of the concepts discussed in this article are general applicable to all Linux distributions, we’ll be demonstrating them in Ubuntu only so ensure to set up an Ubuntu 20.04 server that includes a non-root user with sudo access.

🔭 Want to centralize and monitor your Linux logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

Step 1 — Finding Linux system logs

All Ubuntu system logs are stored in the /var/log directory. Change into this directory in the terminal using the command below:

You can view the contents of this directory by issuing the following command:

You should see a similar output to the following:

alternatives.log auth.log btmp cloud-init-output.log dmesg dpkg.log journal/ landscape/ private/ ubuntu-advantage-license-check.log ubuntu-advantage-timer.log unattended-upgrades/ apt/ bootstrap.log cloud-init.log dist-upgrade/ dmesg.0 faillog kern.log lastlog syslog ubuntu-advantage.log ufw.log wtmp 

Let’s look at a few of the essential system log files that may be present in the /var/log directory and what they contain:

  • /var/log/syslog : stores general information about any global activity in the system.
  • /var/log/auth.log : keeps track of all security-related actions (login, logout, or root user activity).
  • /var/log/kern.log : stores information about events originating from the Linux kernel.
  • /var/log/boot.log : stores system startup messages.
  • /var/log/dmesg : contains messages related to device drivers.
  • /var/log/faillog : keeps track of failed logins, which comes in handy when investigating attempted security breaches.

The /var/log directory is also used to store various application logs. For example, if your distribution is bundled with Apache or MySQL, or installed later, their log files will also be found here.

Читайте также:  Графические пакетные менеджеры linux

Step 2 — Viewing Linux log file contents

Log files contain a large amount of information that are useful for monitoring or analyzing activities performed by the system or a specific application. Therefore, a Linux server administrator must learn the art of reading and understanding the various messages present in log files to effectively diagnose or troubleshoot an issue.

Before we can read log files, we ought to know how they are formatted. Let’s review two basic approaches to log file formatting and storage: plain text and binary files.

Plaintext log files

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

  1. The timestamp indicates the time when a log entry was created in the format MMM dd HH:mm:ss (e.g. Sep 28 19:00:00 ). Notice that this format does not include a year.
  2. Hostname is the host or system that originally create the message.
  3. Application is the application that created the message.
  4. Message contains the actual details of an event.

Let’s go ahead and review some log files in the plaintext format. Run the command below to print the contents of the /var/log/syslog file with the tail utility:

This outputs the last 10 lines of the file:

Mar 23 12:38:09 peter dbus-daemon[1757]: [session uid=1000 pid=1757] Activating via systemd: service name='org.freedesktop.Tracker1' unit='tracker-store.service' requested by ':1.1' (uid=1000 pid=1754 comm="/usr/libexec/tracker-miner-fs " label="unconfined") Mar 23 12:38:09 peter systemd[1743]: Starting Tracker metadata database store and lookup manager. Mar 23 12:38:09 peter dbus-daemon[1757]: [session uid=1000 pid=1757] Successfully activated service 'org.freedesktop.Tracker1' Mar 23 12:38:09 peter systemd[1743]: Started Tracker metadata database store and lookup manager. Mar 23 12:38:40 peter tracker-store[359847]: OK Mar 23 12:38:40 peter systemd[1743]: tracker-store.service: Succeeded. Mar 23 12:39:01 peter CRON[359873]: (root) CMD ( [ -x /usr/lib/php/sessionclean ] && if [ ! -d /run/systemd/system ]; then /usr/lib/php/sessionclean; fi) Mar 23 12:39:23 peter systemd[1]: Starting Clean php session files. Mar 23 12:39:23 peter systemd[1]: phpsessionclean.service: Succeeded. Mar 23 12:39:23 peter systemd[1]: Finished Clean php session files. 

You’ll notice that that each record in this file is formatted in the manner described earlier. For example, the last record has its timestamp as Mar 23 12:39:23, hostname as peter, application as systemd[1] and message as Finished Clean php session files.

If you want to view the entire log file, you can use the cat utility or any text editor such as nano or vim .

Binary log files

While plaintext is the dominant storage format for log files, you will also encounter binary log files that cannot be read with a normal text editor. The /var/log directory contains multiple binary files that are related to the user authorization:

  • /var/log/utmp : tracks users that are currently logged into the system.
  • /var/log/wtmp : tracks previously logged in users. It contains a past data from utmp .
  • /var/log/btmp : tracks failed login attempts.
Читайте также:  Linux top human readable

For these binary logs, special command-line tools are used to display the relevant information in human-readable form. For example, to review the contents of the /var/log/utmp file, run the who utility with -H option (this option causes column labels to be printed in the output table):

Источник

Как посмотреть логи в 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/ — Используется системным демоном безопасности, который управляет удаленным доступом к каталогам и механизмами аутентификации.
Читайте также:  List files and folders linux

Просмотр логов в Linux

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

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

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

Источник

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