Ubuntu логи системы. Просмотр логов в Linux – tail и less

A Linux Administrator should be able to read and understand the various types of messages that are generated by all Linux systems in order to troubleshoot an issue. These messages, called logs, are initiated by Linux and the applications running on it. Linux continuously creates, stores and recycles these logs through various configuration files, programs, commands, and daemons. If you know how to read these files and make optimal use of the various commands we will mention in this tutorial, you can troubleshoot your issues like a pro!

It is important to note that Linux keeps its log files in the /var/log directory in text format.

Viewing System Logs on Ubuntu

In order to reach the core of an issue, or to see if your application or system is behaving in the desired manner, you can view the system log files either graphically or through command line in the following ways:

  • Gnome Logs utility (Graphic)
  • Log File Viewer utility (Graphic)
  • Linux Terminal (Command Line)

View Log Files Through Gnome Logs

‘Logs’ is the default utility that comes with the latest versions of Ubuntu e.g., Ubuntu 18.04 LTS (Bionic Beaver). In order to access it,

Type Logs in the Ubuntu dash:

You will be able to see the Logs utility open, with the option to view logs for Applications, System, Security and Hardware.

Click on the System tab to view system logs:

Here you can view all the system logs along with the time they were generated. You can perform the following actions through this window:

  • Display the contents of a log by clicking on it.
  • Search for a log by clicking the search icon and then providing keywords in the search bar. The search bar also offers a number of filters that you can apply in order to exactly specify What (Select a Journal field to filter the logs according to it) and When (Select the timestamp range of the log entries to be shown) you want to see:

  • You can also export logs to a file by clicking the export button located at the top right corner of the Logs window. You can then save the log file by specifying a name and location.

Through Log File Viewer

The Log File Viewer is the default utility that comes with the older versions of Ubuntu. If your edition of Ubuntu does not have this application by default, you can download and install it through Ubuntu Software.

In order to access the Log File Viewer:

  • Enter Log Viewe r in Ubuntu Dash
  • If you have installed this program through Ubuntu Software, you can launch it by searching for it in the Ubuntu Software as follows and then clicking the Launch button:

The Log File Viewer will appear as follows:


The left panel of the window shows a number of default log categories and the right panel shows a list of logs for the selected category.

Click on the syslog tab to view system logs. You can search for a specific log by using ctrl+F control and then enter the keyword. When a new log event is generated, it is automatically added to the list of logs and you can see it in bolded form. You can also filter your logs through the Filters menu located in the top menu bar.

In order to view a log for a specific application, click the Open option from the File menu. The following Open Log window will open for you to choose the log from:

Click on a log file and click Open . You will now be able to see logs from the selected log file in the Log File Viewer.

View Log Files Through the Terminal

You can also view system logs through the command line, i.e., the Ubuntu Terminal.

Open the Terminal and enter the following command:

This command fetches all the messages from the kernel’s buffer. You can see the output as follows:

You will see that this is a lot of information. This information will only be useful if we apply some filters to view what we want to see.

Customizing dmesg output

  • In order to see messages at your own pace, use the following command:

$ dmesg |less

This command will display only a specific number of messages per screen. You can press Enter in order to move to the next message or press Q to exit the command.

  • In order to search for a message that contains a specific keyword, use the following command:
$ dmesg |grep

For example, if you want to search for all the messages containing the word core, you can use the following command:

$ dmesg |grep core

The Terminal will now display only those messages containing the word “core” in red color.

Open a Log File with cat Command

The dmesg command opens all the logs from the /var/log directory. In order to open the log file from some other location, use the following command:

$ cat

$ cat /var/log/syslog

This command will print logs from the syslog file to the screen. You will again observe that this command prints all the information and it is not easy to skim through. Here again, you can use the ‘grep’ and ‘less’ filters to display the desired output as follows:

$ cat |grep

$ cat |less

Writing To the System Log

Sometimes we need to write custom messages to our system log during the troubleshooting process. Both the Gnome Log and the Log File Viewer programs are built to display a customized message that you can write through the Terminal.

Open the Ubuntu Terminal and type the following command:

$ logger “This is a custom message”


You can see the custom log message, at the end of the above log list, displayed in the graphical log file viewer.

You can also use the logger command within a script for providing additional information. In that case, please use the following command within your script:

$ logger -t scriptname “This is a custom message”

By practicing along with this tutorial, you can learn to troubleshoot your system and application issues by accessing and understanding system logs.

How to View System Log Files on Ubuntu 18.04 LTS

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

Как устроена система регистрации событий?

Опытные системные администраторы знают, что просматривать и анализировать журналы (файлы) регистраций необходимо регулярно и с особой тщательностью. Информация, содержащаяся в журналах очень часто помогает быстро решить возникающие неполадки или выявить скрытые проблемы в конфигурации системы. Для отслеживания событий системой, проверки журналов, учёта, хранения, архивирования и удаления информации из этих журналов должен быть разработан и утверждён специальный регламент для организации, эксплуатирующей и/или обслуживающей системы, серверы и сети.

Основным инструментом регистрации событий в UNIX и Linu до сих пор остаётся демон syslogd системы Syslog. Но следует иметь в виду также и то, что на протяжении длительного времени из-за многообразия всевозможных ответвлений UNIX и версий Linux множество программных пакетов, служебных скриптов, сетевых демонов используют свои собственные журналы, порой отличающимся экзотическим форматом.

В общем случае системой Syslog (и другими специализированными программами) производится перехват отслеживаемого события и регистрация его в файле регистрации. Само регистрируемое событие представляет собой строку текста, содержащую данные о дате/времени, типе, степени важности события. Также в этот набор могут быть, в зависимости от ситуации, включены и другие данные. Сама строка регистрируемого события для выделения указанных компонентов разбивается символами-разделителями: пробелы, табуляции, а также знаками пунктуации.

Журналы регистрации легко просматривать, поскольку они являются обычными текстовыми файлами. Для эффективной работы с журналами используются самые стандартные инструменты из базовой поставки любого дистрибутива - команды и . Если нужно «ворошить» очень большие и сложные по формату журналы, то можно (и даже нужно) вместо утилиты grep использовать другой, гораздо более производительный и гибкий в подобных задачах инструмент - утилиту . Язык обработки текста Perl также очень хорошо подходит для этого.

Типичная запись системного журнала системы Syslog обычно выглядит следующим образом:

Dec 18 15:12:42 backup.main.superhosting.ru sbatchd: sbatchd/main: ls_info() failed: LIM is down; try later; trying ... Dec 18 15:14:28 system.main.superhosting.ru pop-proxy: Connection from 186.115.198.84 Dec 18 15:14:30 control.main.superhosting.ru pingem : office.main.superhosting.ru has not answered 42 times Dec 18 15:15:05 service.main.superhosting.ru vmunix: Multiple softerrors: Seen 100Corrected Softerrors from SIMM J0201 Dec 18 15:15:16 backup.main.superhosting.ru PAM_unix: (sshd) session closed "for user trent

В данном случае можно видеть, что в одном из журналов Syslog собраны события из нескольких источников: программы sbathd, pingem, pop-proxy. Также можно видеть, что события регистрируются для нескольких хостов, взаимодействующих с данной системой: backup, system, office и service.

log файлы и их расположение в Linux

Как уже отмечалось, в системах UNIX и Linux нет чётких соглашений о том, где и как должны храниться журналы регистрации. Они могут быть разбросаны хоть по всей файловой системе, поэтому для каждого администратора важно сразу разобраться, где и для каких пакетов и демонов находятся соответствующие файлы журналов. Но несмотря на отсутствие чётких формальных регламентов относительно мест хранения журналов, всё же существует традиционно сложившееся правило, что эти файлы должны находиться в каталогах /var/log, /var/log/syslog, а также в /var/adm.

Как правило, доступ для чтения файлов в указанных каталогах предоставляется только суперпользователю, однако нет ничего страшного, если для часто просматриваемых журналов, в которых также нет важной системной информации настроить более «демократический» режим доступа. Обычно к такому варианту также прибегают для удобства и экономии времени, когда нужно часто и регулярно изучать некоторые журналы, например для веб-сервера Apache, которые обычно находятся в /var/log/apache2 или /var/log/httpd.

Стоит также помнить и о том, что бывают случаи, когда (особенно на сбойных конфигурациях) общий объём файлов журналов резко увеличивается, при этом велик риск «уложить» систему. Для удобства контроля за свободным пространством на устройствах хранения, а также для надёжности каталог /var часто выносят в отдельную файловую систему на отдельном разделе.

Некоторые специальные файлы журналов

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

Файл Программа Место Частота Системы Назначение
acpid acpid Ф 64к RZ События, связанные с системой питания
auth.log sudo и прочие S М U Информация об авторизации
apache2/* httpd или apache2 Ф Д ZU Журналы веб-сервера Apache
apt* APT Ф М U Установщики пакетов
boot.log Сценарии запуска Ф М R Логи сценариев запуска
boot.msg Ядро В - Z Образ буфера сообщений ядра
cron, cron S Н RAH Логи и сведения о работе демона cron
cups/* CUPS Ф Н ZRU Сообщения, связанные с системой печати
daemon.log Разное S Н U Сообщения средств демонов
debug Разное S Д U Сообщения для отладки
dmesg Ядро В - RU Образ буфера сообщений ядра
dpkg.log dpkg Ф М U Установщики пакетов
faillog login Н Н RZU Информация о неудачных попытках авторизации
apache2/* Httpd или apache2 Ф Д R Журналы веб-сервера Apache для каталога /etc
kern.log login В - RZ Все сообщения средств ядра
lastlog login В - RZ Время последней регистрации в системе каждого пользователя (этот файл бинарный)
mail* Программы электронной почты S Н Все Сообщения средств электронной
messages Разное S Н RZUS
rpmpkgs cron.daily В Д R Список установленных RPM-пакетов
samba/* smbd и прочие Ф Н - Сведения о работе сервера Samba
secure sshd и прочие S М R Конфиденциальные авторизационные сообщения
sulog su Ф - SAH Сведения об удачных и неудачных попыток использования команды su
syslog* Разное S H SUH Основной системный журнальный файл
warn wpar S H Z События уровня системных предупреждений/ошибок
wpars/* wpar Ф - А Сведения о событиях загрузочных разделов
wtmp login В M Все Сообщения о регистрации в системе (бинарный файл)
xen/* Xen Ф 1m RZU Информация от монитора виртуальных машин Xen
Xorg.n.log Xorg Ф Н RS Сообщения об ошибках сервера X Windows
yum.log yum Ф М R Журнал управления пакетом

Для данной таблицы действуют следующие обозначения: S - Syslog, В - встроенное имя, Ф - конфигурационный файл, Д - ежедневно, Н - еженедельно, М - ежемесячно, NN - размер в килобайтах или мегабайтах, Z - SUSE, R - Red Hat и CentOS, S - Solaris, H - HP-UX, A - AIX. В столбце «Частота» указывается частота, с которой удаляется устаревшая информация, связанная со временем или с объёмом файла. В столбце «Программа» указывается программа, создающая файл.

Следует отметить также, что большая часть сообщений для представленных в таблице файлов направляется в систему Syslog. Уровень критичности и программа, создающая файл задаются в конфигурационном файле /etc/initlog.conf. - так работает система Syslog. Файл faillog является двоичным, и поэтому может быть прочтён утилитой failog.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter .

Лог файл (файл журнала), как вы наверное догадались, сохраняет хронологию событий для операционной системы Linux, её приложений и служб.

Файлы хранятся в виде обычного текста, чтобы их можно было легко читать. В нашей статье мы расскажем, где найти лог файлы, приведем в пример несколько основных файлов журнала и объясним, как их читать.

Где находятся лог файлы в Linux

Файлы журналов Linux обычно хранятся в папке /var / logs.

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

Например, когда команда ls выполняется к примеру в папке /var/logs, вот несколько доступных журналов:

  • kern.log
  • auth.log
  • bootstrap.log
  • alternatives.log
  • samba
  • lightdm

Последние три из этого списке являются папками, но у них есть также есть файлы журнала.

Поскольку лог файлы находятся в текстовом формате, их можно прочитать, введя следующую команду:

Приведенная выше команда открывает файл журнала в редакторе nano. Если лог файл имеет небольшой размер, то нет ничего лучше, чем открыть файл журнала в редакторе, но если файл журнала большой, то вас, вероятно, интересует только конец журнала.

Можно указать, сколько строк должно отображаться с помощью параметра -n следующим образом:

Если же вы хотите увидеть начало файла, вы можете использовать команду head.

Основные системные журналы

Следующие лог файлы являются основными в Linux.

  • Журнал авторизации
  • Журнал демонов
  • Журнал отладки
  • Журнал ядра
  • Системный журнал

Журнал демонов (daemon.log) отслеживает службы, работающие в фоновом режиме и выполняющие важные задачи. Демоны, как правило, не выводятся на экране.

Журнал отладки предоставляет вывод отладок для приложений.

Журнал ядра содержит подробные сведения о ядре Linux.

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

Анализ содержимого файла журнала

Изображение выше показывает содержание последних 50 файлов в файле системного журнала (syslog).

Каждая строка журнала содержит следующие данные:

  • Имя хоста
  • Служба/Приложение
  • Сообщение

Пример одной из строк в файле syslog:

jan 20 12:28:56 gary-virtualbox systemd: starting cups scheduler

Ротация логов

Файлы журнала периодически меняются, чтобы они не становились слишком большими.

Утилита log rotate отвечает за ротацию файлов журнала. Вы можете определить, что журнал был заменен, потому что его название будет содержать число, такое как auth.log.1, auth.log.2.

Можно изменить частоту замены журнала, отредактировав файл /etc/logrotate.conf.

Ниже показан пример записей из файла logrotate.conf:

#rotate log files
weekly

#keep 4 weeks worth of log files

create new log files after rotating

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

При замене файла журнала на его месте создается новый файл.

Каждое приложение может иметь свою собственную политику ротации. Это, определенно, полезно, потому что файл системного журнала будет расти быстрее, чем файл журнала cups.

Политики ротации хранятся в /etc/logrotate.d. У каждого приложения, для которого требуется собственная политика ротации, в папке с приложением будет храниться файл конфигурации.

Например, инструмент apt содержит файл в папке logrotate.d со следующим содержанием:

/var/log/apt/history.log {
rotate 12
monthly
compress
missingok
notifempty
}

В принципе, этот журнал говорит вам следующее. Журнал будет хранить лог файлы в течение 12 недель и будет меняться каждый месяц (по одному в месяц). Файл журнала будет сжат. Если в журнал не записываются сообщения (т.е. он пуст), это нормально. Журнал не будет заменяться на новый, если он пустой.

Чтобы изменить политику файла, замените его параметры на нужные вам, а затем выполните следующую команду:

Нашли опечатку? Выделите текст и нажмите Ctrl + Enter

Наконец сегодня вырвал из работы какое-то время, чтобы посвятить его очень полезной информации. Речь пойдет о системных логах-logs Ubuntu (журналах). Так как читкой логов занимаются в основном системные администраторы, то я эту статью размещаю в разделе "Администрирование Ubuntu " .

Что же такое Log files ???

Файл регистрации , протокол , журнал или лог (англ. log ) - файл с записями о событиях в хронологическом порядке.

Лог-файлы сервера - специальные файлы, в которых протоколируются все действия пользователя на сервере. В лог-файлы сервера попадает информация, откуда пришел тот либо иной посетитель, когда и сколько времени он провел на сайте, что там смотрел и скачивал, какой у него браузер и какой IP-адрес у его компьютера. Каждая запись в лог-файле соответствует определенному хиту, так как сервер может фиксировать именно запрос к одному из элементов сайта. Проанализировав лог-файлы, можно получить сводные цифры активности пользователей, изучить закономерности поведения групп пользователей и оценить эффективность рекламной кампании.

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

Исследование содержимого файла регистрации ошибок после возникновения неполадок часто позволяет понять их причины.

Лог файлы различных приложений

Тут собраны пусть не все, но основные Log Files. Все журналы находятся в каталоге /var/log :

  • /арасhе2/ - журналы Web-сервера Apache2;
  • /cups/ - журналы системы печати;
  • /gdm/ - журналы менеджера дисплея;
  • /installer/ - журналы программы установки;
  • /news/ - журналы NNTP-сервера и NNTP-клиентов;
  • /proftpd/ - журналы FTP-сервера;
  • auth.log - журнал аутентификации (кто и когда входил в систему);
  • daemons.log - журнал для разных демонов (служб);
  • dmesg - загрузочные сообщения ядра;
  • dpkg.log - журнал программы dpkg;
  • kem.log - журнал сообщений ядра;
  • mail * - журналы почтовой службы;
  • messages - различные сообщения ядра (и в некоторых случаях - обычных программ);
  • secure - журнал службы безопасности;
  • syslog - журнал демона syslog;
  • Xorg.O.log - журнал системы XFree86;
  • user.log - различные сообщения программ пользовательского уровня.

Протоколирование сообщений системы и программ выполняется двумя демонами - klogd и syslogd . Первый протоколирует сообщения ядра, а второй - все остальные сообщения, поэтому никогда не отключайте эти демоны. Файл dmesg создается самим ядром при начальной загрузке системы.
Имена файлов журналов могут немного отличаться от приведенных выше, поскольку имена журналов зависят от настроек системы, в том числе и от настроек syslogd . К тому же у вас могут быть дополнительные файлы протоколов или даже каталоги, содержащие файлы протоколов, - повторюсь, все зависит от настроек системы. Чтобы узнать, какие файлы протоколов у вас являются основными, откройте файл конфигурации syslogd - /etc/syslog.conf . Прочитав его, вы узнаете, какие файлы протоколирования есть в вашей системе и для чего они используются.
Но в файле конфигурации /etc/syslogd.conf перечислены далеко не все файлы протоколов. Многие серверы ведут свои журналы, имена файлов которых вы можете узнать в файле конфигурации того или иного сервера.
В каком же журнале искать ошибку? Тут нужно исходить из принципа взаимоисключения: если у вас не работает Web-сервер Apache , то искать причину нужно в каталоге /var/log/apache2/ , но никак не в файле /var/log/user.log .
Сообщения различных программ пользовательского уровня, т. е. обычных программ, возможно, запущенных с привилегиями root , протоколируются в файл /var/log/user.log.

Introduction

One of the things which makes GNU/Linux a great operating system is that virtually anything and everything happening on and to the system may be logged in some manner. This information is invaluable for using the system in an informed manner, and should be one of the first resources you use to trouble-shoot system and application issues. The logs can tell you almost anything you need to know, as long as you have an idea where to look first.

Your Ubuntu system provides vital information using various system log files. These log files are typically plain ASCII text in a standard log file format, and most of them sit in the traditional system log subdirectory /var/log . Many are generated by the system log daemon, syslogd on behalf of the system and certain applications, while some applications generate their own logs by writing directly to files in /var/log .

This guide talks about how to read and use several of these system log files, how to use and configure the system logging daemon, syslogd , and how log rotation works. See the Resources section for additional information.

Target Audience

This guide will be simple enough to use if you have any experience using the console and editing text files using a text editor. See the end of this document for some essential commands that may help you find your way around these files if you"re relatively new to the command line.

System Logs

System logs deal primarily with the functioning of the Ubuntu system, not necessarily with additional applications added by users. Examples include authorization mechanisms, system daemons, system messages, and the all-encompassing system log itself, syslog .

Authorization Log

The Authorization Log tracks usage of authorization systems, the mechanisms for authorizing users which prompt for user passwords, such as the Pluggable Authentication Module (PAM) system, the sudo command, remote logins to sshd and so on. The Authorization Log file may be accessed at /var/log/auth.log . This log is useful for learning about user logins and usage of the sudo command.

Use grep to cut down on the volume. For example, to see only information in the Authorization Log pertaining to sshd logins, use this:

grep sshd /var/log/auth.log | less

Daemon Log

A daemon is a program that runs in the background, generally without human intervention, performing some operation important to the proper running of your system. The daemon log at /var/log/daemon.log and contains information about running system and application daemons such as the Gnome Display Manager daemon gdm , the Bluetooth HCI daemon hcid , or the MySQL database daemon mysqld . This can help you trouble-shoot problems with a particular daemon.

Again, use grep to find specific information, plugging in the name of the daemon you"re interested in.

Debug Log

The debug log at /var/log/debug and provides detailed debug messages from the Ubuntu system and applications which log to syslogd at the DEBUG level.

Kernel Log

The kernel log at /var/log/kern.log provides a detailed log of messages from the Ubuntu Linux kernel. These messages may prove useful for trouble-shooting a new or custom-built kernel, for example.

Kernel Ring Buffer

The kernel ring buffer is not really a log file per se, but rather an area in the running kernel you can query for kernel bootup messages via the dmesg utility. To see the messages, use this:

dmesg | less

Or to search for lines that mention the Plug & Play system, for example, use grep like this:

dmesg | grep pnp | less

By default, the system initialization script /etc/init.d/bootmisc.sh sends all bootup messages to the file /var/log/dmesg as well. You can view and search this file the usual way.

System Log

The system log typically contains the greatest deal of information by default about your Ubuntu system. It is located at /var/log/syslog , and may contain information other logs do not. Consult the System Log when you can"t locate the desired log information in another log. It also contains everything that used to be in /var/log/messages .

Application Logs

Many applications also create logs in /var/log . If you list the contents of your /var/log subdirectory, you will see familiar names, such as /var/log/apache2 representing the logs for the Apache 2 web server, or /var/log/samba , which contains the logs for the Samba server. This section of the guide introduces some specific examples of application logs, and information contained within them.

Apache HTTP Server Logs

The default installation for Apache2 on Ubuntu creates a log subdirectory: /var/log/apache2 . Within this subdirectory are two log files with two distinct purposes:

    /var/log/apache2/access.log - records of every page served and every file loaded by the web server.

    /var/log/apache2/error.log - records of all error conditions reported by the HTTP server

By default, every time Apache accesses a file or page, the access logs record the IP address, time and date, browser identification string, HTTP result code and the text of the actual query, which will generally be a GET for a page view. Look at the Apache documentation for a complete rundown; quite a lot can be gleaned from this file, and indeed many statistical packages exist that perform analyses of these logs.

Also, every time any error occurs, Apache adds a line to the error log. If you run PHP with error and warning messages disabled, this can be your only way to identify bugs.

CUPS Print System Logs

The Common Unix Printing System (CUPS) uses the default log file /var/log/cups/error_log to store informational and error messages. If you need to solve a printing issue in Ubuntu, this log may be a good place to start.

Rootkit Hunter Log

The Rootkit Hunter utility (rkhunter) checks your Ubuntu system for backdoors, sniffers and rootkits, which are all signs of compromise of your system. The log rkhunter uses is located at /var/log/rkhunter.log .

Samba SMB Server Logs

The Server Message Block Protocol (SMB) server, Samba is popularly used for sharing files between your Ubuntu computer and other computers which support the SMB protocol. Samba keeps three distinct types of logs in the subdirectory /var/log/samba:

    log.nmbd - messages related to Samba"s NETBIOS over IP functionality (the network stuff)

    log.smbd - messages related to Samba"s SMB/CIFS functionality (the file and print sharing stuff)

    log. - messages related to requests for services from the IP address contained in the log file name, for example, log.192.168.1.1 .

X11 Server Log

The default X11 Windowing Server in use with Ubuntu is the Xorg X11 server, and assuming your computer has only one display defined, it stores log messages in the file /var/log/Xorg.0.log . This log is helpful for diagnosing issues with your X11 environment.

Non-Human-Readable Logs

Some log files found in the /var/log subdirectory are designed to be readable by applications, not necessarily by humans. Some examples of such log files which appear in /var/log follow.

Login Failures Log

The login failures log located at /var/log/faillog is actually designed to be parsed and displayed by the faillog command. For example, to print recent login failures, use this:

faillog

Last Logins Log

The last logins log at /var/log/lastlog should not typically be parsed and examined by humans, but rather should be used in conjunction with the lastlog command. For example to see a listing of logins with the lastlog command, displayed one page per screen with the less command, use the following command:

lastlog | less

Login Records Log

The file /var/log/wtmp contains login records, but unlike /var/log/lastlog above, /var/log/wtmp is not used to show a list of recent logins, but is instead used by other utilities such as the who command to present a listed of currently logged in users. This command will show the users currently logged in to your machine:

who

System Logging Daemon (syslogd)

The system logging daemon syslogd , also known as sysklogd , awaits logging messages from numerous sources and routes the messages to the appropriate file or network destination. Messages logged to syslogd usually contain common elements like system hostnames and time-stamps in addition to the specific log information.

Configuration of syslogd

The syslogd daemon"s configuration file is /etc/syslog.conf . Each entry in this file consists of two fields, the selector and the action. The selector field specifies a facility to be logged, such as for example the auth facility which deals with authorization, and a priority level to log such information at, such as info , or warning . The action field consists of a target for the log information, such as a standard log file (i.e. /var/log/syslog), or the hostname of a remote computer to send the log information to.

Echoing Messages to syslogd With Logger

A neat utility exists in the logger tool, which allows one to place messages into the System Log (i.e. /var/log/syslog) arbitrarily. For example, assume your user name is buddha , and you would like to enter a message into the syslog about a particularly delicious pizza you"re eating, you could use a command such as the following at a terminal prompt:

logger This Pizza from Vinnys Gourmet Rocks

and you would end up with a line in the /var/log/syslog file like this:

Jan 12 23:34:45 localhost buddha: This Pizza from Vinnys Gourmet Rocks

You can even specify a tag the messages come from, and redirect the output standard error too.

# # sample logger error jive # logmsg="/usr/bin/logger -s -t MyScript " # announce what this script is, even to the log $logmsg "Directory Checker FooScript Jive 1.0" # test for the existence of Fred"s home dir on this machine if [ -d /home/fred ]; then $logmsg "I. Fred"s Home Directory Found" else $logmsg "E. Fred"s Home Directory was NOT Found. Boo Hoo." exit 1 fi

Executing this script as chkdir.sh on the machine butters where Fred does not have a home directory, /home/fred , gives the following results:

bumpy@butters:~$./chkdir.sh MyScript: Directory Checker FooScript Jive 1.0 MyScript: E. Fred"s Home Directory was NOT Found. Boo Hoo. bumpy@butters:~$tail -n 2 /var/log/syslog Jan 12 23:23:11 localhost MyScript: Directory Checker FooScript Jive 1.0 Jan 12 23:23:11 localhost MyScript: E. Fred"s Home Directory was NOT Found. Boo Hoo.

So, as you can see, we received the messages both via standard error, at the terminal prompt, and they also appear in our syslog.

Log Rotation

When viewing directory listings in /var/log or any of its subdirectories, you may encounter log files with names such as daemon.log.0 , daemon.log.1.gz , and so on. What are these log files? They are "rotated" log files. That is, they have automatically been renamed after a predefined time-frame, and a new original log started. After even more time the log files are compressed with the gzip utility as in the case of the example daemon.log.1.gz . The purpose of log rotation is to archive and compress old logs so that they consume less disk space, but are still available for inspection as needed. What handles this functionality? Why, the logrotate command of course! Typically, logrotate is called from the system-wide cron script /etc/cron.daily/logrotate , and further defined by the configuration file /etc/logrotate.conf . Individual configuration files can be added into /etc/logrotate.d (where the apache2 and mysql configurations are stored for example).

This guide will not cover the myriad of ways logrotate may be configured to handle the automatic rotation of any log file on your Ubuntu system. For more detail, check the Resources section of this guide.

NOTE: You may also rotate system log files via the cron.daily script /etc/cron.daily/sysklogd instead of using logrotate. Actually, the utility savelog may produce unexpected results on log rotation which configuring logrotate seems to have no effect on. In those cases, you should check the cron.daily sysklogd script in /etc/cron.daily/sysklogd and read the savelog manual page to see if savelog is not in fact doing the rotation in a way that is not what you are specifying with logrotate .

Essential Commands

If you"re new to the console and the Linux command line, these commands will get you up and running to the point where you can work with log files at a basic level.

Getting Started

To change to the log directory, where most of these files sit, use the cd command. This saves having to type out a full path name for every subsequent command:

cd /var/log

Editing Files

You can view and edit files in GEdit or Kate, the simple text editors that come with Ubuntu and Kubuntu respectively, but these can be overkill when all you want to do is look at a file or make simple changes. The easiest editor to use from the console is nano, which is less powerful but also less complicated than vim or emacs. The command to edit a particular logfile /var/log/example.log using nano is:

nano example.log

Press Ctrl+X to exit. It will ask if you want to save your changes when you exit, but unless you run it with the sudo command the files won"t be writable. In general, you won"t want to save your changes to log files, of course.

Viewing Files

To simply look at a file, an editor is overkill. Use the less command, which pages through a file one screen at a time:

less example.log

You don"t need sudo to look at a file. Press h for help, or q to quit. The cursor keys and page up/down keys will work as expected, and the slash key ("/") will do a case-sensitive search; the n key repeats the last search.

Viewing the Beginning of Files

To see the first ten lines of a file, use the head command:

head example.log

To see some other number of lines from the beginning of the file, add the -n switch, thus:

head -n 20 example.log

Viewing the End of Files

To see the final ten lines of a file, the analogous command is tail:

tail example.log

Again, the -n switch gives you control over how many lines it displays:

tail -n 20 example.log

Watching a Changing File

Also, the -f ("follow") switch puts tail into a loop, constantly waiting for new additions to the file it"s displaying. This is useful for monitoring files that are being updated in real time:

tail -f example.log

Press Ctrl+C to quit the loop.

Searching Files

Because log files can be large and unwieldy, it helps to be able to focus. The grep command helps you strip out only the content you care about. To find all the lines in a file containing the word "system", for example, use this:

grep "system" example.log

To find all the lines containing "system" at the beginning of the line, use this:

grep "^system" example.log

Note the caret symbol, a regular expression that matches only the start of a line. This is less useful for standard log files, which always start with a date and time, but it can be handy otherwise. Not all files have a standard format.

Any time the result of a grep is still too long, you can pipe it through less:

grep "system" example.log | less

Resources

Additional information on system and application logs and syslogd is available via the following resources:

Local System Resources

System manual page for the dmesg kernel ring buffer utility

System manual page for the faillog command (and also the faillog configuration file via man 5 faillog)

System manual page for the grep pattern searching utility

System manual page for the head utility

System manual page for the kernel log daemon (klogd)

System manual for the last command which shows last logged in users

System manual page for the less paging utility

System manual page for the logger command-line interface to syslog utility

System manual page for the the logrotate utility

System manual page for the savelog log file saving utility

System manual page for the system log daemon (syslogd)

System manual page for the syslogd configuration file

System manual page for the tail utility