20.2. Basic Configuration of Rsyslog

The main configuration file for rsyslog is /etc/rsyslog.conf. Here, you can specify global directives, modules, and rules that consist of filter and action parts. Also, you can add comments in the form of text following a hash sign (#).

20.2.1. Filters

A rule is specified by a filter part, which selects a subset of syslog messages, and an action part, which specifies what to do with the selected messages. To define a rule in your /etc/rsyslog.conf configuration file, define both, a filter and an action, on one line and separate them with one or more spaces or tabs.
rsyslog offers various ways to filter syslog messages according to selected properties. The available filtering methods can be divided into Facility/Priority-based, Property-based, and Expression-based filters.
Facility/Priority-based filters
The most used and well-known way to filter syslog messages is to use the facility/priority-based filters which filter syslog messages based on two conditions: facility and priority separated by a dot. To create a selector, use the following syntax:
  • FACILITY specifies the subsystem that produces a specific syslog message. For example, the mail subsystem handles all mail-related syslog messages. FACILITY can be represented by one of the following keywords (or by a numerical code): kern (0), user (1), mail (2), daemon (3), auth (4), syslog (5), lpr (6), news (7), uucp (8), cron (9), authpriv (10), ftp (11), and local0 through local7 (16 - 23).
  • PRIORITY specifies a priority of a syslog message. PRIORITY can be represented by one of the following keywords (or by a number): debug (7), info (6), notice (5), warning (4), err (3), crit (2), alert (1), and emerg (0).
    The aforementioned syntax selects syslog messages with the defined or higher priority. By preceding any priority keyword with an equal sign (=), you specify that only syslog messages with the specified priority will be selected. All other priorities will be ignored. Conversely, preceding a priority keyword with an exclamation mark (!) selects all syslog messages except those with the defined priority.
In addition to the keywords specified above, you may also use an asterisk (*) to define all facilities or priorities (depending on where you place the asterisk, before or after the comma). Specifying the priority keyword none serves for facilities with no given priorities. Both facility and priority conditions are case-insensitive.
To define multiple facilities and priorities, separate them with a comma (,). To define multiple selectors on one line, separate them with a semi-colon (;). Note that each selector in the selector field is capable of overwriting the preceding ones, which can exclude some priorities from the pattern.

Example 20.1. Facility/Priority-based Filters

The following are a few examples of simple facility/priority-based filters that can be specified in /etc/rsyslog.conf. To select all kernel syslog messages with any priority, add the following text into the configuration file:
To select all mail syslog messages with priority crit and higher, use this form:
To select all cron syslog messages except those with the info or debug priority, set the configuration in the following form:
Property-based filters
Property-based filters let you filter syslog messages by any property, such as timegenerated or syslogtag. For more information on properties, see Section 20.2.3, “Properties”. You can compare each of the specified properties to a particular value using one of the compare-operations listed in Table 20.1, “Property-based compare-operations”. Both property names and compare operations are case-sensitive.
Property-based filter must start with a colon (:). To define the filter, use the following syntax:
  • The PROPERTY attribute specifies the desired property.
  • The optional exclamation point (!) negates the output of the compare-operation. Other Boolean operators are currently not supported in property-based filters.
  • The COMPARE_OPERATION attribute specifies one of the compare-operations listed in Table 20.1, “Property-based compare-operations”.
  • The STRING attribute specifies the value that the text provided by the property is compared to. This value must be enclosed in quotation marks. To escape certain character inside the string (for example a quotation mark (")), use the backslash character (\).

Table 20.1. Property-based compare-operations

Compare-operation Description
contains Checks whether the provided string matches any part of the text provided by the property. To perform case-insensitive comparisons, use contains_i.
isequal Compares the provided string against all of the text provided by the property. These two values must be exactly equal to match.
startswith Checks whether the provided string is found exactly at the beginning of the text provided by the property. To perform case-insensitive comparisons, use startswith_i.
regex Compares the provided POSIX BRE (Basic Regular Expression) against the text provided by the property.
ereregex Compares the provided POSIX ERE (Extended Regular Expression) regular expression against the text provided by the property.
isempty Checks if the property is empty. The value is discarded. This is especially useful when working with normalized data, where some fields may be populated based on normalization result.

Example 20.2. Property-based Filters

The following are a few examples of property-based filters that can be specified in /etc/rsyslog.conf. To select syslog messages which contain the string error in their message text, use:
:msg, contains, "error"
The following filter selects syslog messages received from the host name host1:
:hostname, isequal, "host1"
To select syslog messages which do not contain any mention of the words fatal and error with any or no text between them (for example, fatal lib error), type:
:msg, !regex, "fatal .* error"
Expression-based filters
Expression-based filters select syslog messages according to defined arithmetic, Boolean or string operations. Expression-based filters use rsyslog's own scripting language called RainerScript to build complex filters.
The basic syntax of expression-based filter looks as follows:
  • The EXPRESSION attribute represents an expression to be evaluated, for example: $msg startswith 'DEVNAME' or $syslogfacility-text == 'local0'. You can specify more than one expression in a single filter by using and and or operators.
  • The ACTION attribute represents an action to be performed if the expression returns the value true. This can be a single action, or an arbitrary complex script enclosed in curly braces.
  • Expression-based filters are indicated by the keyword if at the start of a new line. The then keyword separates the EXPRESSION from the ACTION. Optionally, you can employ the else keyword to specify what action is to be performed in case the condition is not met.
With expression-based filters, you can nest the conditions by using a script enclosed in curly braces as in Example 20.3, “Expression-based Filters”. The script allows you to use facility/priority-based filters inside the expression. On the other hand, property-based filters are not recommended here. RainerScript supports regular expressions with specialized functions re_match() and re_extract().

Example 20.3. Expression-based Filters

The following expression contains two nested conditions. The log files created by a program called prog1 are split into two files based on the presence of the "test" string in the message.
if $programname == 'prog1' then {
   action(type="omfile" file="/var/log/prog1.log")
   if $msg contains 'test' then
     action(type="omfile" file="/var/log/prog1test.log")
     action(type="omfile" file="/var/log/prog1notest.log")
See Section 20.12, “Online Documentation” for more examples of various expression-based filters. RainerScript is the basis for rsyslog's new configuration format, see Section 20.3, “Using the New Configuration Format”

20.2.2. Actions

Actions specify what is to be done with the messages filtered out by an already-defined selector. The following are some of the actions you can define in your rule:
Saving syslog messages to log files
The majority of actions specify to which log file a syslog message is saved. This is done by specifying a file path after your already-defined selector:
where FILTER stands for user-specified selector and PATH is a path of a target file.
For instance, the following rule is comprised of a selector that selects all cron syslog messages and an action that saves them into the /var/log/cron.log log file:
cron.* /var/log/cron.log
By default, the log file is synchronized every time a syslog message is generated. Use a dash mark (-) as a prefix of the file path you specified to omit syncing:
Note that you might lose information if the system terminates right after a write attempt. However, this setting can improve performance, especially if you run programs that produce very verbose log messages.
Your specified file path can be either static or dynamic. Static files are represented by a fixed file path as shown in the example above. Dynamic file paths can differ according to the received message. Dynamic file paths are represented by a template and a question mark (?) prefix:
FILTER ?DynamicFile
where DynamicFile is a name of a predefined template that modifies output paths. You can use the dash prefix (-) to disable syncing, also you can use multiple templates separated by a colon (;). For more information on templates, see Section 20.2.3, “Generating Dynamic File Names”.
If the file you specified is an existing terminal or /dev/console device, syslog messages are sent to standard output (using special terminal-handling) or your console (using special /dev/console-handling) when using the X Window System, respectively.
Sending syslog messages over the network
rsyslog allows you to send and receive syslog messages over the network. This feature allows you to administer syslog messages of multiple hosts on one machine. To forward syslog messages to a remote machine, use the following syntax:
  • The at sign (@) indicates that the syslog messages are forwarded to a host using the UDP protocol. To use the TCP protocol, use two at signs with no space between them (@@).
  • The optional zNUMBER setting enables zlib compression for syslog messages. The NUMBER attribute specifies the level of compression (from 1 – lowest to 9 – maximum). Compression gain is automatically checked by rsyslogd, messages are compressed only if there is any compression gain and messages below 60 bytes are never compressed.
  • The HOST attribute specifies the host which receives the selected syslog messages.
  • The PORT attribute specifies the host machine's port.
When specifying an IPv6 address as the host, enclose the address in square brackets ([, ]).

Example 20.4. Sending syslog Messages over the Network

The following are some examples of actions that forward syslog messages over the network (note that all actions are preceded with a selector that selects all messages with any priority). To forward messages to via the UDP protocol, type:
*.* @
To forward messages to "example.com" using port 6514 and the TCP protocol, use:
*.* @@example.com:6514
The following compresses messages with zlib (level 9 compression) and forwards them to 2001:db8::1 using the UDP protocol
*.* @(z9)[2001:db8::1]
Output channels
Output channels are primarily used to specify the maximum size a log file can grow to. This is very useful for log file rotation (for more information see Section 20.2.5, “Log Rotation”). An output channel is basically a collection of information about the output action. Output channels are defined by the $outchannel directive. To define an output channel in /etc/rsyslog.conf, use the following syntax:
  • The NAME attribute specifies the name of the output channel.
  • The FILE_NAME attribute specifies the name of the output file. Output channels can write only into files, not pipes, terminal, or other kind of output.
  • The MAX_SIZE attribute represents the maximum size the specified file (in FILE_NAME) can grow to. This value is specified in bytes.
  • The ACTION attribute specifies the action that is taken when the maximum size, defined in MAX_SIZE, is hit.
To use the defined output channel as an action inside a rule, type:
FILTER :omfile:$NAME

Example 20.5. Output channel log rotation

The following output shows a simple log rotation through the use of an output channel. First, the output channel is defined via the $outchannel directive:
 $outchannel log_rotation, /var/log/test_log.log, 104857600, /home/joe/log_rotation_script
and then it is used in a rule that selects every syslog message with any priority and executes the previously-defined output channel on the acquired syslog messages:
*.* :omfile:$log_rotation
Once the limit (in the example 100 MB) is hit, the /home/joe/log_rotation_script is executed. This script can contain anything from moving the file into a different folder, editing specific content out of it, or simply removing it.
Sending syslog messages to specific users
rsyslog can send syslog messages to specific users by specifying a user name of the user you want to send the messages to (as in Example 20.7, “Specifying Multiple Actions”). To specify more than one user, separate each user name with a comma (,). To send messages to every user that is currently logged on, use an asterisk (*).
Executing a program
rsyslog lets you execute a program for selected syslog messages and uses the system() call to execute the program in shell. To specify a program to be executed, prefix it with a caret character (^). Consequently, specify a template that formats the received message and passes it to the specified executable as a one line parameter (for more information on templates, see Section 20.2.3, “Templates”).
Here an output of the FILTER condition is processed by a program represented by EXECUTABLE. This program can be any valid executable. Replace TEMPLATE with the name of the formatting template.

Example 20.6. Executing a Program

In the following example, any syslog message with any priority is selected, formatted with the template template and passed as a parameter to the test-program program, which is then executed with the provided parameter:
*.* ^test-program;template


When accepting messages from any host, and using the shell execute action, you may be vulnerable to command injection. An attacker may try to inject and execute commands in the program you specified to be executed in your action. To avoid any possible security threats, thoroughly consider the use of the shell execute action.
Storing syslog messages in a database
Selected syslog messages can be directly written into a database table using the database writer action. The database writer uses the following syntax:
  • The PLUGIN calls the specified plug-in that handles the database writing (for example, the ommysql plug-in).
  • The DB_HOST attribute specifies the database host name.
  • The DB_NAME attribute specifies the name of the database.
  • The DB_USER attribute specifies the database user.
  • The DB_PASSWORD attribute specifies the password used with the aforementioned database user.
  • The TEMPLATE attribute specifies an optional use of a template that modifies the syslog message. For more information on templates, see Section 20.2.3, “Templates”.


Currently, rsyslog provides support for MySQL and PostgreSQL databases only. In order to use the MySQL and PostgreSQL database writer functionality, install the rsyslog-mysql and rsyslog-pgsql packages, respectively. Also, make sure you load the appropriate modules in your /etc/rsyslog.conf configuration file:
$ModLoad ommysql    # Output module for MySQL support
$ModLoad ompgsql    # Output module for PostgreSQL support
For more information on rsyslog modules, see Section 20.6, “Using Rsyslog Modules”.
Alternatively, you may use a generic database interface provided by the omlibdb module (supports: Firebird/Interbase, MS SQL, Sybase, SQLLite, Ingres, Oracle, mSQL).
Discarding syslog messages
To discard your selected messages, use the tilde character (~).
The discard action is mostly used to filter out messages before carrying on any further processing. It can be effective if you want to omit some repeating messages that would otherwise fill the log files. The results of discard action depend on where in the configuration file it is specified, for the best results place these actions on top of the actions list. Please note that once a message has been discarded there is no way to retrieve it in later configuration file lines.
For instance, the following rule discards any cron syslog messages:
cron.* ~

Specifying Multiple Actions

For each selector, you are allowed to specify multiple actions. To specify multiple actions for one selector, write each action on a separate line and precede it with an ampersand (&) character:
Specifying multiple actions improves the overall performance of the desired outcome since the specified selector has to be evaluated only once.

Example 20.7. Specifying Multiple Actions

In the following example, all kernel syslog messages with the critical priority (crit) are sent to user user1, processed by the template temp and passed on to the test-program executable, and forwarded to via the UDP protocol.
kern.=crit user1
& ^test-program;temp
& @
Any action can be followed by a template that formats the message. To specify a template, suffix an action with a semicolon (;) and specify the name of the template. For more information on templates, see Section 20.2.3, “Templates”.


A template must be defined before it is used in an action, otherwise it is ignored. In other words, template definitions should always precede rule definitions in /etc/rsyslog.conf.

20.2.3. Templates

Any output that is generated by rsyslog can be modified and formatted according to your needs with the use of templates. To create a template use the following syntax in /etc/rsyslog.conf:
$template TEMPLATE_NAME,"text %PROPERTY% more text", [OPTION]
  • $template is the template directive that indicates that the text following it, defines a template.
  • TEMPLATE_NAME is the name of the template. Use this name to refer to the template.
  • Anything between the two quotation marks ("") is the actual template text. Within this text, special characters, such as \n for new line or \r for carriage return, can be used. Other characters, such as % or ", have to be escaped if you want to use those characters literally.
  • The text specified between two percent signs (%) specifies a property that allows you to access specific contents of a syslog message. For more information on properties, see Section 20.2.3, “Properties”.
  • The OPTION attribute specifies any options that modify the template functionality. The currently supported template options are sql and stdsql, which are used for formatting the text as an SQL query.


    Note that the database writer checks whether the sql or stdsql options are specified in the template. If they are not, the database writer does not perform any action. This is to prevent any possible security threats, such as SQL injection.
    See section Storing syslog messages in a database in Section 20.2.2, “Actions” for more information.

Generating Dynamic File Names

Templates can be used to generate dynamic file names. By specifying a property as a part of the file path, a new file will be created for each unique property, which is a convenient way to classify syslog messages.
For example, use the timegenerated property, which extracts a time stamp from the message, to generate a unique file name for each syslog message:
$template DynamicFile,"/var/log/test_logs/%timegenerated%-test.log"
Keep in mind that the $template directive only specifies the template. You must use it inside a rule for it to take effect. In /etc/rsyslog.conf, use the question mark (?) in an action definition to mark the dynamic file name template:
*.* ?DynamicFile


Properties defined inside a template (between two percent signs (%)) enable access various contents of a syslog message through the use of a property replacer. To define a property inside a template (between the two quotation marks ("")), use the following syntax:
  • The PROPERTY_NAME attribute specifies the name of a property. A list of all available properties and their detailed description can be found in the rsyslog.conf(5) manual page under the section Available Properties.
  • FROM_CHAR and TO_CHAR attributes denote a range of characters that the specified property will act upon. Alternatively, regular expressions can be used to specify a range of characters. To do so, set the letter R as the FROM_CHAR attribute and specify your desired regular expression as the TO_CHAR attribute.
  • The OPTION attribute specifies any property options, such as the lowercase option to convert the input to lowercase. A list of all available property options and their detailed description can be found in the rsyslog.conf(5) manual page under the section Property Options.
The following are some examples of simple properties:
  • The following property obtains the whole message text of a syslog message:
  • The following property obtains the first two characters of the message text of a syslog message:
  • The following property obtains the whole message text of a syslog message and drops its last line feed character:
  • The following property obtains the first 10 characters of the time stamp that is generated when the syslog message is received and formats it according to the RFC 3999 date standard.

Template Examples

This section presents a few examples of rsyslog templates.
Example 20.8, “A verbose syslog message template” shows a template that formats a syslog message so that it outputs the message's severity, facility, the time stamp of when the message was received, the host name, the message tag, the message text, and ends with a new line.

Example 20.8. A verbose syslog message template

$template verbose, "%syslogseverity%, %syslogfacility%, %timegenerated%, %HOSTNAME%, %syslogtag%, %msg%\n"
Example 20.9, “A wall message template” shows a template that resembles a traditional wall message (a message that is send to every user that is logged in and has their mesg(1) permission set to yes). This template outputs the message text, along with a host name, message tag and a time stamp, on a new line (using \r and \n) and rings the bell (using \7).

Example 20.9. A wall message template

$template wallmsg,"\r\n\7Message from syslogd@%HOSTNAME% at %timegenerated% ...\r\n %syslogtag% %msg%\n\r"
Example 20.10, “A database formatted message template” shows a template that formats a syslog message so that it can be used as a database query. Notice the use of the sql option at the end of the template specified as the template option. It tells the database writer to format the message as an MySQL SQL query.

Example 20.10. A database formatted message template

$template dbFormat,"insert into SystemEvents (Message, Facility, FromHost, Priority, DeviceReportedTime, ReceivedAt, InfoUnitID, SysLogTag) values ('%msg%', %syslogfacility%, '%HOSTNAME%', %syslogpriority%, '%timereported:::date-mysql%', '%timegenerated:::date-mysql%', %iut%, '%syslogtag%')", sql
rsyslog also contains a set of predefined templates identified by the RSYSLOG_ prefix. These are reserved for the syslog's use and it is advisable to not create a template using this prefix to avoid conflicts. The following list shows these predefined templates along with their definitions.
A special format used for troubleshooting property problems.
"Debug line with all properties:\nFROMHOST: '%FROMHOST%', fromhost-ip: '%fromhost-ip%', HOSTNAME: '%HOSTNAME%', PRI: %PRI%,\nsyslogtag '%syslogtag%', programname: '%programname%', APP-NAME: '%APP-NAME%', PROCID: '%PROCID%', MSGID: '%MSGID%',\nTIMESTAMP: '%TIMESTAMP%', STRUCTURED-DATA: '%STRUCTURED-DATA%',\nmsg: '%msg%'\nescaped msg: '%msg:::drop-cc%'\nrawmsg: '%rawmsg%'\n\n\"
The format specified in IETF's internet-draft ietf-syslog-protocol-23, which is assumed to become the new syslog standard RFC.
A modern-style logfile format similar to TraditionalFileFormat, but with high-precision time stamps and time zone information.
"%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n\"
The older default log file format with low-precision time stamps.
"%TIMESTAMP% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n\"
A forwarding format with high-precision time stamps and time zone information.
"%PRI%%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag:1:32%%msg:::sp-if-no-1st-sp%%msg%\"
The traditional forwarding format with low-precision time stamps.
"%PRI%%TIMESTAMP% %HOSTNAME% %syslogtag:1:32%%msg:::sp-if-no-1st-sp%%msg%\"

20.2.4. Global Directives

Global directives are configuration options that apply to the rsyslogd daemon. They usually specify a value for a specific predefined variable that affects the behavior of the rsyslogd daemon or a rule that follows. All of the global directives must start with a dollar sign ($). Only one directive can be specified per line. The following is an example of a global directive that specifies the maximum size of the syslog message queue:
$MainMsgQueueSize 50000
The default size defined for this directive (10,000 messages) can be overridden by specifying a different value (as shown in the example above).
You can define multiple directives in your /etc/rsyslog.conf configuration file. A directive affects the behavior of all configuration options until another occurrence of that same directive is detected. Global directives can be used to configure actions, queues and for debugging. A comprehensive list of all available configuration directives can be found in Section 20.12, “Online Documentation”. Currently, a new configuration format has been developed that replaces the $-based syntax (see Section 20.3, “Using the New Configuration Format”). However, classic global directives remain supported as a legacy format.

20.2.5. Log Rotation

The following is a sample /etc/logrotate.conf configuration file:
# rotate log files weekly
# keep 4 weeks worth of backlogs
rotate 4
# uncomment this if you want your log files compressed
All of the lines in the sample configuration file define global options that apply to every log file. In our example, log files are rotated weekly, rotated log files are kept for four weeks, and all rotated log files are compressed by gzip into the .gz format. Any lines that begin with a hash sign (#) are comments and are not processed.
You may define configuration options for a specific log file and place it under the global options. However, it is advisable to create a separate configuration file for any specific log file in the /etc/logrotate.d/ directory and define any configuration options there.
The following is an example of a configuration file placed in the /etc/logrotate.d/ directory:
/var/log/messages {
    rotate 5
    /usr/bin/killall -HUP syslogd
The configuration options in this file are specific for the /var/log/messages log file only. The settings specified here override the global settings where possible. Thus the rotated /var/log/messages log file will be kept for five weeks instead of four weeks as was defined in the global options.
The following is a list of some of the directives you can specify in your logrotate configuration file:
  • weekly — Specifies the rotation of log files to be done weekly. Similar directives include:
    • daily
    • monthly
    • yearly
  • compress — Enables compression of rotated log files. Similar directives include:
    • nocompress
    • compresscmd — Specifies the command to be used for compressing.
    • uncompresscmd
    • compressext — Specifies what extension is to be used for compressing.
    • compressoptions — Specifies any options to be passed to the compression program used.
    • delaycompress — Postpones the compression of log files to the next rotation of log files.
  • rotate INTEGER — Specifies the number of rotations a log file undergoes before it is removed or mailed to a specific address. If the value 0 is specified, old log files are removed instead of rotated.
  • mail ADDRESS — This option enables mailing of log files that have been rotated as many times as is defined by the rotate directive to the specified address. Similar directives include:
    • nomail
    • mailfirst — Specifies that the just-rotated log files are to be mailed, instead of the about-to-expire log files.
    • maillast — Specifies that the about-to-expire log files are to be mailed, instead of the just-rotated log files. This is the default option when mail is enabled.
For the full list of directives and various configuration options, see the logrotate(5) manual page.