Monitor Linux logs in real time. Log files Linux in order Linux writing log to file

As you know, Linux has a very important sysklogd tool that allows you to keep a log of events occurring in the system. System administrators, and indeed any user who encounters errors, will have to look linux logs to identify the problem and solve it.

All linux log files located in the folder:
/var/log

Linux log files:
messages Contains global Linux system logs, including those logged at system startup.
dmesg Contains messages received from the kernel. Registers many messages at the boot stage, they display information about hardware devices that are initialized during the boot process. The number of messages in the log is limited, and when the file is full, with each new message, the old ones will be overwritten.
auth.log Contains information about user authorization in the system, including user logins and authentication mechanisms that have been used.
boot.log Contains information that is logged when the system boots.
daemon.log Includes messages from various background daemons
kern.log Also contains messages from the kernel, useful in troubleshooting user modules built into the kernel.
lastlog Displays information about the last session of all users. This is a non-text file and must be viewed using the lastlog command.
mail.log logs of the email server running on the system.
user.log Information from all logs at the user level.
Xorg.x.log X server message log.
btmp Contains information about failed login attempts.
cups All messages related to printing and printers.
cron Whenever the cron daemon starts running a program, it writes the report and messages of the program itself to this file.
secure Contains information related to authentication and authorization.
wtmp Contains the user logon log. Use the wtmp command to display the contents of this file.
faillog Contains failed login attempts. Use the faillog command to display the contents of this file.
mysqld.log Contains MySQL database server log files.

You can view linux logs using several console programs. Let's take a look at a few examples below:

1. Displaying and scrolling text with less:
less /var/log/messages

2. View logs in real time:
tail -f /var/log/messages

3. Open the file with cat:
cat /var/log/dmesg

4. Output the first 10 lines from the file:
head /var/log/dmesg

5. Output the last 10 lines from the file:
tail /var/log/dmesg

6. Output a certain number of lines:
head -n3 /var/log/dmesg
where, -n3 is the number of lines to display.

7. Display only errors:
grep -i error /var/log/messages

In addition to the console and text editors, you can also use the graphical program "System Log Viewer", which will show you in a convenient and visual form logs in linux.

Managing Log files on a Linux System

Linux's Log Files

All Linux systems generate systems logs that can be inspected to find information about your running system. These log files can contain a wealth of information from simple information messages to critical system issues. Most of the logging files that are created are in plain text. This means that it is very easy to view these using standard commands such as "more", "less", "cat", "head", "tail", "pg" or by using your preferred text editor such as "vi or vim".


By convention, most of the log files that are created are found under the directory "/var/log/". This is a standard area where system messages and logged/recorded. Depending on which Linux distribution you are using you will probably have a "message" file or a "syslog" file that contains recent activity. Logfiles are generally created by either a "syslogd" or "rsyslogd" logging demon. These demons are highly configurable and can filter messages into specified files. As well as handling local events, it is possible to log messages to remote servers dedicated to receiving these type of messages. It is quite common within larger organizations to have a dedicated syslog server. Some basic configuration options will be covered later. It is also common practice to have some form of log rotation process.

Below is a list of some of the more common log files that you will find. Some of these are distribution specific:


log file Description
/var/log/messages Global system messages are logged here. (default logging area on some systems)
/var/log/syslog Global System messages are logged here. (default logging area on some systems)
/var/log/auth.log System Authorization information, including user login information
/var/log/kern.log Kernel messages are logged here
/var/log/mail.log Contains logging information from your mail server
/var/log/boot.log System boot messages are logged here
/var/log/cups.log Printer related messages logged here
/var/log/wtmp Contains information relating to users logged onto your system
/var/log/samba Samba log files for smbd and nmbd. If configured can contain specific log files for users.
/var/log/dpkg.log Contains information from installations that use dpkg to install or remove a package
/var/log/zypper.log Contains messages from zypper package manager tool
/var/log/apt Contains information from package updates that use APT
/var/log/dmesg Contains Kernel ring buffer messages

Although the above is not an exhaustive view of all the files that can be found within the "/var/log" area. It does give you a rough idea of ​​what is logged. It is important to remember that many third part products (software) will also write to this area. Often a sub-directory is created with various log information held within. Samba is a good example of this.

As mentioned earlier it is the "syslogd" or "rsyslogd" daemon that handles the majority of logging on your systems.

rsyslogd - logging utility

Rsyslogd is a reliable extended version of the syslogd service. Linux uses rsyslogd as its mechanism to record log files either in a central area or split into separate directories for clarity. It is also possible to send information to a dedicated logging server. Multiple processes may write to the same area without causing file locking. Simple commands can be used directly from scripts to write to this area.

Configuration Files

How rsyslogd behaves on your system is down to its configuration. This file is generally located in "/etc/rsyslog.conf". This file contains text which describes what should happen to messages when they are logged. It is here that you can specify specific directories for specific message types. Default logging rules are generally located under "/etc/rsyslog.d/"

Example of rsyslogd.conf under Ubuntu

/etc/rsyslog.conf


# Default logging rules can be found in /etc/rsyslog.d/50-default.conf ################# #### MODULES #### #### ############# $ModLoad imuxsock # provides support for local system logging $ModLoad imklog # provides kernel logging support (previously done by rklogd) #$ModLoad immark # provides --MARK-- message capability # provides UDP syslog reception #$ModLoad imudp #$UDPServerRun 514 # provides TCP syslog reception #$ModLoad imtcp #$InputTCPServerRun 514 ######################## ### #### GLOBAL DIRECTIVES #### ########################## # # Use traditional timestamp format. # To enable high precision timestamps, comment out the following line. # $ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat # Filter duplicated messages $RepeatedMsgReduction on # # Set the default permissions for all log files. # $FileOwner syslog $FileGroup adm $FileCreateMode 0640 $DirCreateMode 0755 $Umask 0022 $PrivDropToUser syslog $PrivDropToGroup syslog # # Where to place spool files # $WorkDirectory /var/spool/rsyslog # # Include all config files in /etc/rsyslog. d/ # $IncludeConfig /etc/rsyslog.d/*.conf

Hashes "#" are used to denote a comment or for commenting out a function that is not required.
notice the last line $IncludeConfig /etc/rsyslog.d/*.conf. This is where we can specify custom rules/mappings.


# Default rules for rsyslog. # # For more information see rsyslog.conf(5) and /etc/rsyslog.conf # # First some standard log files. Log by facility. # auth,authpriv.* /var/log/auth.log *.*;auth,authpriv.none -/var/log/syslog #cron.* /var/log/cron.log #daemon.* -/var/ log/daemon.log kern.* -/var/log/kern.log #lpr.* -/var/log/lpr.log mail.* -/var/log/mail.log #user.* -/var/ log/user.log # # Logging for the mail system. Split it up so that # it is easy to write scripts to parse these files. # #mail.info -/var/log/mail.info #mail.warn -/var/log/mail.warn mail.err /var/log/mail.err # # Logging for INN news system. # news.crit /var/log/news/news.crit news.err /var/log/news/news.err news.notice -/var/log/news/news.notice # # Some "catch-all" log files. # #*.=debug;\ # auth,authpriv.none;\ # news.none;mail.none -/var/log/debug #*.=info;*.=notice;*.=warn;\ # auth ,authpriv.none;\ # cron,daemon.none;\ # mail,news.none -/var/log/messages # # Emergencies are sent to everybody logged in. # *.emerg:omusrmsg:* # # I like to have messages displayed on the console, but only on a virtual # console I usually leave idle. # #daemon,mail.*;\ # news.=crit;news.=err;news.=notice;\ # *.=debug;*.=info;\ # *.=notice;*.=warn /dev /tty8 # The named pipe /dev/xconsole is for the `xconsole" utility. To use it, # you must invoke `xconsole" with the `-file" option: # # $ xconsole -file /dev/xconsole [.. .] # # NOTE: adjust the list below, or you"ll go crazy if you have a reasonably # busy site.. # daemon.*;mail.*;\ news.err;\ *.=debug;*.= info;\ *.=notice;*.=warn |/dev/xconsole

The default logging area is called "syslog", see below exert


*.*;auth,authpriv.none -/var/log/syslog

What are Facilities and Levels?

Whenever the rsyslogd daemon receives a logging message, it acts based on the message type (Facility) and a Level (Priority). These mappings can be seen in your "/etc/syslog.conf" file or your included "/etc/syslog.d/*.conf" files.

Each entry within the configuration file can specify one or more facility/level selectors followed by an action. A selector consists of a facility or facilities followed by a single action. Action is normally the name of the directory and file that is to receive the messages into.

facility.level action

Example: mail.* -/var/log/mail- Here, "mail" is the facility, level is set to "*" and action is "/var/log/mail"

Facility

A facility represents the creator of the message, these normally consist of:

auth, authpriv, cron, daemon, kern, lpr, mail, mark, news, syslog, user, local0 - local7, " * " signifies any facility

These facilities give us the ability to control where messages from certain sources are sent to. The facilities local0 - local7 are for use by your own scripts.

Level (Priority)

The level specifies the severity threshold. These can be: (lowest priority first)

debug, info, notice, warning, err, crit, alert, emerg.

On older systems you may see "warn, error or panic". A level of none will disable the associated facility. These priorities control the amount of detail that is sent to each logfile. A single period "." separates the facility from the level. Together these are known as the message selector . An asterisk" * " may be used to specify all facilities or levels. Similar to facilities, wildcards "*" can be used along with "none". Only one level or wildcard may be specified with each selector. The following modifiers may be used " = "and" ! "

If you specify only one level within a selector without any modifiers, you are actually specifying that level plus all other priorities. For example the selector user notice is actually saying all user related messages having a level of notice or higher will be sent to the specified action area. If you require only a level of "notice", then you will have to use the " = modifier:

user.=notice- Now means any user related messages with a level priority of "notice" only will be sent to the relevant logging area.

If you use the" ! " modifier, this will negate your level priority. So if we specified user.!notice is the equivalent of all user related messages with a level priority of "notice" or higher. You can also specify user.!=notice which specify all user related messages except for those with the level priority of "notice".

Actions

The action section is the destination for the messages. The action can be a filename such as "/var/log/syslog" or a hostname or IP address prefixed with the "@" sign. The latter option is popular in large organizations and enterprises. Quite often security related messages may be sent to a central logging server for further scrutiny.

rsyslog.conf structures

As rsyslogd is an enhanced version of the syslogd it can handle the older legacy style constructs known as syslogd. It also handles legacy versions of rsyslog. However, the true power of rsyslog comes into play when you use what is known as " RainerScript". This is the new style format for rsyslog which can handle complex cases with ease. In the example below you can see old format entries along with newer entries that use "if - then" constructs for a more precise handling.

Example section of "/etc/rsyslog.conf taken from openSUSE


# # NetworkManager into separate file and stop their further processing # if ($programname == "NetworkManager") or \ ($programname startswith "nm-") ​​\ then -/var/log/NetworkManager & ~ # # email-messages # mail.* -/var/log/mail mail.info -/var/log/mail.info mail.warning -/var/log/mail.warn mail.err /var/log/mail.err # # news-messages # news.crit - /var/log/news/news.crit news.err - /var/log/news/news.err news.notice - /var/log/news/news.notice

Message Testing with the logger command

logger is a shell command interface into the syslog module. Logger allows you to make entries directly into the system log. This is very useful when incorporated into a script or when you want to test your message selector and mappings.

In its simplest form we can issue logger "I am a test". This message would then go to our default area (probably /var/log/syslog or /var/log/messages) depending on how you have configured your rules. You can also specify a priority using the "-p or --priority" option. Examples of logger action:


[email protected]:/var/log$ logger "I am a Test of logger" Mar 22 22:39:51 john-desktop kernel: [ 9588.319477] dev_remove_pack: edad0884 not found. Mar 22 22:45:01 john-desktop CRON: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1) Mar 22 22:47:31 john-desktop john: I am a Test logger

Basic Logger Usage

Usage: logger Options: -d, --udp use UDP (TCP is default) -i, --id log the process ID too -f, --file log the contents of this file -h, --help display this help text and exit -n, --server write to this remote syslog server -P, --port use this UDP port -p, --priority Mark given message with this priority -s, --stderr output message to standard error as well -t, --tag mark every line with this tag -u, --socket write to this Unix socket -V, --version output version information and exit

Getting help with Rsyslog

The above is intended as an overview to the processes that takes place for logging of messages to occur. For further information you can issue "man rsyslogd" from your console for an overview of the many options. For further reading you can head to the main "rsyslog" website: www.rsyslog.com

dmesg

"dmesg" is a special command that stands for display message. dmesg will display the message buffer of the kernel. dmesg is very useful if you want to view the messages that flew past your screen quickly during the boot process. Another useful trick is to redirect the output from the dmesg command to a temporary file: dmesg > /tmp/temp.txt.

dmesg is also useful if you are having issues with an I/O device or a "USB" device. dmesg can be used in combination with the grep command to find exactly what you are looking for quickly: dmesg | grep -i usb

dmesg basic Overview

Usage: dmesg Options: -C, --clear clear the kernel ring buffer -c, --read-clear read and clear all messages -D, --console-off disable printing messages to console -d, --show-delta show time delta between printed messages -E, --console-on enable printing messages to console -f, --facility restrict output to defined facilities -h, --help display this help and exit -k, --kernel display kernel messages -l, --level restrict output to defined levels -n, --console-level set level of messages printed to console -r, --raw print the raw message buffer -s, --buffer-size buffer size to query the kernel ring buffer -T, --ctime show human readable timestamp (could be inaccurate if you have used SUSPEND/RESUME) -t, --notime don"t print messages timestamp -u, --userspace display userspace messages -V, --version output version information and exit -x, --decode decode facility and level to readable string Supported log facilities: kern - kernel messages user - random user-level messages mail - mail system daemon - system daemons auth - security/authorization messages syslog - messages generated internally by syslogd lpr - line printer subsystem news - network news subsystem Supported log levels (priorities): emerg - system is unusable alert - action must be taken immediately crit - critical conditions err - error conditions warn - warning conditions notice - normal but significant condition info - informational debug - debug-level messages

Finally took some time out of work today to devote some very useful information to it. We are talking about Ubuntu system logs (logs). Since system administrators are mainly engaged in reading logs, I place this article in the section "Ubuntu Administration".

What is log files???

Registration file, protocol, magazine or log(English) log ) - a file with records of events in chronological order.

Server log files- special files that record all user actions on the server. The server log files contain information about where a particular visitor came from, when and how much time he spent on the site, what he watched and downloaded there, what browser he has and what IP address his computer has. Each entry in the log file corresponds to a specific hit, since the server can fix exactly the request to one of the site elements. After analyzing the log files, you can get summary figures of user activity, study the patterns of behavior of user groups and evaluate the effectiveness of an advertising campaign.

Record keeping , or logging , - chronological record with different (adjustable) level of detail of information about events occurring in the system (errors, warnings, messages), usually to a file.

Examining the contents of the error log after a problem has occurred can often lead to an understanding of the cause.

Log files of various applications

Not all, but the main Log Files are collected here. All logs are in the /var/log directory:

  • /apache2/ - Apache2 web server logs;
  • /cups/ - journals of the printing system;
  • /gdm/ - display manager logs;
  • /installer/ - installer logs;
  • /news/ - NNTP server and NNTP client logs;
  • /proftpd/ - FTP server logs;
  • auth.log - authentication log (who logged in and when);
  • daemons.log - log for different daemons (services);
  • dmesg - kernel boot messages;
  • dpkg.log - dpkg program log;
  • kem.log - kernel message log;
  • mail * - mail service logs;
  • messages - various kernel messages (and in some cases - regular programs);
  • secure - security service log;
  • syslog - syslog daemon log;
  • Xorg.O.log - XFree86 system log;
  • user.log - various messages from user-level programs.

Logging system and program messages is performed by two daemons - klogd and syslogd. The former logs kernel messages and the latter logs all other messages, so never disable these daemons. File dmesg created by the kernel itself when the system boots.
The names of the log files may differ slightly from the above, as the names of the logs depend on the system settings, including the settings syslogd. In addition, you may have additional log files or even directories containing log files - again, it all depends on the system settings. To find out which log files you have are the main ones, open the configuration file syslogd- /etc/syslog.conf . After reading it, you will know what log files are on your system and what they are used for.
But not all log files are listed in the /etc/syslogd.conf configuration file. Many servers keep their own logs, the file names of which you can find in the configuration file of a particular server.
In what log to look for an error? Here you need to proceed from the principle of mutual exclusion: if it does not work for you Apache web server, then you need to look for the reason in the /var/log/apache2/ directory, but not in the /var/log/user.log file.
Messages from various user-level programs, i.e. regular programs, possibly running with privileges root, are logged to the /var/log/user.log file.

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 analyzes 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 Login 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:

last log | less

Login Record 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:

[email protected]:~$./chkdir.sh MyScript: Directory Checker FooScript Jive 1.0 MyScript: E. Fred's Home Directory was NOT Found. Boo Hoo. [email protected]:~$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 details, 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 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

In the course of its work, the system tracks and saves in special files some events that it considers important or simply necessary for use in order to correct and debug errors, failed configurations, etc. The files in which these events are stored are called log files or registration files . It is not uncommon for log files to take up too much disk space, which can be indicative of a system malfunction, configuration errors, or simply a misconfiguration of the event logging daemons that monitor and collect everything in a row. Thus, working with the event registration system is an important component in the work of any system administrator, on which the quality of system maintenance and, as a result, their reliability and durability entirely depend.

How is the event registration system arranged?

Experienced system administrators know that it is necessary to view and analyze logs (files) of registrations regularly and with great care. The information contained in the logs very often helps to quickly solve problems that arise or reveal hidden problems in the system configuration. To track events by the system, check logs, record, store, archive and delete information from these logs, a special regulation must be developed and approved for the organization operating and / or maintaining systems, servers and networks.

The main event logging tool in UNIX and Linu is still the syslogd daemon of the Syslog system. But it should also be borne in mind that for a long time, due to the variety of various branches of UNIX and Linux versions, many software packages, service scripts, network daemons use their own logs, sometimes differing in an exotic format.

In the general case, the Syslog system (and other specialized programs) intercepts the monitored event and logs it in the log file. The registered event itself is a text string containing data on the date/time, type, and degree of importance of the event. Other data may also be included in this set, depending on the situation. The line of the registered event itself is divided by delimiter characters: spaces, tabs, as well as punctuation marks to highlight the specified components.

Logs are easy to view as they are plain text files. For effective work with logs, the most standard tools from the basic delivery of any distribution kit are used - the and commands. If you need to "tear" very large and complex logs, then you can (and even need) instead of the grep utility, use another tool that is much more productive and flexible in such tasks - the utility. The Perl text processing language is also very well suited for this.

A typical system syslog entry usually looks like this:

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

In this case, you can see that one of the Syslog logs contains events from several sources: sbathd, pingem, pop-proxy programs. You can also see that events are being logged for several hosts that interact with this system: backup, system, office, and service.

log files and their location in Linux

As already noted, UNIX and Linux systems do not have clear agreements on where and how logs should be stored. They can be scattered even throughout the entire file system, so it is important for every administrator to immediately understand where and for which packages and daemons the corresponding log files are located. But despite the absence of clear formal regulations regarding where logs are stored, there is still a traditionally established rule that these files should be located in the /var/log, /var/log/syslog directories, and also in /var/adm.

As a rule, access to read files in these directories is granted only to the superuser, but there is nothing to worry about if logs that are frequently viewed, which also do not contain important system information, are set to a more “democratic” access mode. This option is also usually used for convenience and time saving when you need to frequently and regularly examine some logs, for example for the Apache web server, which are usually located in /var/log/apache2 or /var/log/httpd.

It is also worth remembering that there are cases when (especially on failed configurations) the total volume of log files increases dramatically, while there is a high risk of "laying down" the system. For the convenience of controlling free space on storage devices, as well as for reliability, the /var directory is often moved to a separate file system on a separate partition.

Some special log files

The following table lists some of the log files that are very useful for system administration:

File Program Place Frequency Systems Purpose
acpid acpid F 64k RZ Power System Events
auth.log sudo and others S M U Authorization information
apache2/* httpd or apache2 F D ZU Apache web server logs
apt* APT F M U Package Installers
boot.log Launch scripts F M R Launch script logs
boot.msg Nucleus AT - Z Kernel message buffer image
cron, cron S H RAH Logs and information about the work of the cron daemon
cups/* CUPS F H ZRU Messages related to the printing system
daemon.log Miscellaneous S H U Daemon Tool Messages
debug Miscellaneous S D U Debugging messages
dmesg Nucleus AT - EN Kernel message buffer image
dpkg.log dpkg F M U Package Installers
faillog login H H RZU Information about failed login attempts
apache2/* httpd or apache2 F D R Apache web server logs for the /etc directory
kern.log login AT - RZ All kernel tool messages
lastlog login AT - RZ Last login time of each user (this file is binary)
mail* Email programs S H All Messages of means of electronic
messages Miscellaneous S H RZUS
rpmpkgs cron daily AT D R List of installed RPMs
samba/* smbd and others F H - Understanding the operation of the Samba server
secure sshd and others S M R Confidential authorization messages
sulog su F - SAH Success and failure details of the su command
syslog* Miscellaneous S H SUH Main system log file
warn wpar S H Z System warning/error level events
wpars/* wpar F - BUT About boot partition events
wtmp login AT M All Login Messages (Binary)
xen/* Xen F 1m RZU Information from the Xen Virtual Machine Monitor
xorg.n.log Xorg F H RS X Windows Server Error Messages
yum.log yum F M R Package Control Log

The following notations apply to this table: S - Syslog, B - built-in name, F - configuration file, D - daily, H - weekly, M - monthly, NN - size in kilobytes or megabytes, Z - SUSE, R - Red Hat and CentOS, S - Solaris, H - HP-UX, A - AIX. The "Frequency" column indicates the frequency with which obsolete information related to time or file size is deleted. The Program column indicates the program that creates the file.

It should also be noted that most of the messages for the files presented in the table are sent to the Syslog system. The severity level and the program that creates the file are specified in the /etc/initlog.conf configuration file. - this is how the Syslog system works. The faillog file is binary and therefore can be read by the failog utility.

If you find an error, please highlight a piece of text and click Ctrl+Enter.