CONTENT
  • CHANGES
Szukaj
counter

#top Syslog / Rsyslog


W systemie Linux w dystrybucji CentOS w wersji 5.* dostępny jest syslog w wersji 1.4.*:
sysklogd-1.4.1-44.el5
Dostępny w systemie Linux w dystrybucji CentOS 5.* syslog w wersji 1.4.* uruchamiany jest w formie dwóch demonów: syslogd oraz klogd.
Demon klogd odpowiada za przechwytywanie i logowanie komunikatów pochodzących z jądra systemu operacyjnego Linux.
Demon syslogd odpwiada za przechwytywanie i logowanie komunikatów przekazywanych przez bibliotekę systemową.

W systemie Linux w dystrybucji CentOS 6.* oraz CentOS 7.* dostępny jest rsyslog w wersji 4.* i wyższych (syslog został zastąpiony przez rsyslog):
rsyslog-4.6.2-12.el6
rsyslog-7.4.7-12.el7
Dostępny systemie Linux w dystrybucji CentOS 6.* oraz CentOS 7.* rsyslog w wersji 4.* i wyższych uruchamiany jest w formie jednego demona rsyslogd (syslog został zastąpiony przez rsyslog, reliable and extended syslogd):
Demon rsyslogd odpowiada zarówno za przechwytywanie i logowanie komunikatów pochodzących z jądra systemu operacyjnego Linux jak również za przechwytywanie i logowanie komunikatów przekazywanych przez bibliotekę systemową.

The facility is one of the following keywords: auth, authpriv, cron, daemon, kern, lpr, mail, mark, news, security (same as auth), syslog, user, uucp and local0 through local7. The keyword security should not be used anymore and mark is only for internal use and therefore should not be used in applications. Anyway, you may want to specify and redirect these messages here. The facility specifies the subsystem that produced the message, i.e. all mail programs log with the mail facility (LOG_MAIL) if they log using syslog.
Zgodnie z dokumentacją dostępne są następujące (rozpoznawalne przez demona syslogd) źródła:
  • auth
  • authpriv
  • cron
  • daemon
  • kern
  • lpr
  • mail
  • mark
  • news
  • security (same as auth)
  • syslog
  • user
  • uucp
  • local0
  • local1
  • local2
  • local3
  • local4
  • local5
  • local6
  • local7

The priority is one of the following keywords, in ascending order: debug, info, notice, warning, warn (same as warning), err, error (same as err), crit, alert, emerg, panic (same as emerg). The keywords error, warn and panic are deprecated and should not be used anymore. The priority defines the severity of the message
Zgodnie z dokumentacją dostępne są następujące (rozpoznawalne przez demona syslogd) priorytety:
  • debug
  • info
  • notice
  • warning
  • warn (same as warning)
  • err
  • error (same as err)
  • crit
  • alert
  • emerg
  • panic (same as emerg)



#top syslog RFC


The BSD syslog Protocol
https://tools.ietf.org/html/rfc3164

Reliable Delivery for syslog
https://tools.ietf.org/html/rfc3195

The Syslog Protocol
https://tools.ietf.org/html/rfc5424



#top /etc/sysconfig/syslog


Konfiguracja demona syslogd znajduje się w pliku konfiguracyjnym /etc/syslog.conf w przypadku zastosowania innej lokalizacji niezbędne jest przekazanie tej informacji demonowi w postaci argumentu -f /path/to/syslog-file.conf. Niniejszą informację należy umieścić w zmiennej SYSLOGD_OPTIONS zdefiniowanej w pliku /etc/sysconfig/syslog wczytywanym przez skrypt startowy demona. Dostępny po instalacji plik /etc/sysconfig/syslog wygląda analogicznie jak poniżej:
# Options to syslogd
# -m 0 disables 'MARK' messages.
# -r enables logging from remote machines
# -x disables DNS lookups on messages recieved with -r
# See syslogd(8) for more details
SYSLOGD_OPTIONS="-m 0"
# Options to klogd
# -2 prints all kernel oops messages twice; once for klogd to decode, and
#    once for processing with 'ksymoops'
# -x disables all klogd processing of oops messages entirely
# See klogd(8) for more details
KLOGD_OPTIONS="-x"
#
SYSLOG_UMASK=077
# set this to a umask value to use for all log files as in umask(1).
# By default, all permissions are removed for "group" and "other".



#top syslogd


Strony man: syslogd - Linux system logging utilities

SYNOPSIS
syslogd [ -a socket ] [ -d ] [ -f config file ] [ -h ] [ -l hostlist ] [ -m interval ] [ -n ] [ -p socket ] [ -r ] [ -s domainlist ] [ -v ] [ -x ]

Poniżej przedstawiono argumenty, które można przekazać demonowi syslogd podczas uruchamiania by zmienić jego zachowanie:
OPTIONS
-a socket
Using this argument you can specify additional sockets from that syslogd has to listen to. This is needed if you're going to let some daemon run within a chroot() environment. You can use up to 19 additional sockets. If your environment needs even more, you have to increase the symbol MAXFUNIX within the syslogd.c source file. An example for a chroot() daemon is described by the people from OpenBSD at http://www.psionic.com/papers/dns.html.

-d
Turns on debug mode. Using this the daemon will not proceed a fork(2) to set itself in the background, but opposite to that stay in the foreground and write much debug information on the current tty. See the DEBUGGING section for more information.

-f config file
Specify an alternative configuration file instead of /etc/syslog.conf, which is the default.

-h
By default syslogd will not forward messages it receives from remote hosts. Specifying this switch on the command line will cause the log daemon to forward any remote messages it receives to forwarding hosts which have been defined.

-l hostlist
Specify a hostname that should be logged only with its simple hostname and not the fqdn. Multiple hosts may be specified using the colon (":") separator.

-m interval
The syslogd logs a mark timestamp regularly. The default interval between two -- MARK -- lines is 20 minutes. This can be changed with this option. Setting the interval to zero turns it off entirely.

-n
Avoid auto-backgrounding. This is needed especially if the syslogd is started and controlled by init(8).

-p socket
You can specify an alternative unix domain socket instead of /dev/log.

-r
This option will enable the facility to receive message from the network using an internet domain socket with the syslog service (see services(5)). The default is to not receive any messages from the network.

This option is introduced in version 1.3 of the sysklogd package. Please note that the default behavior is the opposite of how older versions behave, so you might have to turn this on.

-s domainlist
Specify a domainname that should be stripped off before logging. Multiple domains may be specified using the colon (":") separator. Please be advised that no sub-domains may be specified but only entire domains. For example if -s north.de is specified and the host logging resolves to satu.infodrom.north.de no domain would be cut, you will have to specify two domains like: -s north.de:infodrom.north.de.

-S
Verbose logging. If specified once, the numeric facility and priority are logged with each locally-written message. If specified more than once, the names of the facility and priority are logged with each locally-written message.

-v
Print version and exit.

-x
Disable name lookups when receiving remote messages. This avoids deadlocks when the nameserver is running on the same machine that runs the syslog daemon.



#top klogd


Strony man: klogd - Kernel Log Daemon

SYNOPSIS
klogd [ -c n ] [ -d ] [ -f fname ] [ -iI ] [ -n ] [ -o ] [ -p ] [ -s ] [ -k fname ] [ -v ] [ -x ] [ -2 ]

Poniżej przedstawiono argumenty, które można przekazać demonowi klogd podczas uruchamiania by zmienić jego zachowanie:
OPTIONS
-c n
Sets the default log level of console messages to n.

-d
Enable debugging mode. This will generate LOTS of output to stderr.

-f file
Log messages to the specified filename rather than to the syslog facility.

-i -I
Signal the currently executing klogd daemon. Both of these switches control the loading/reloading of symbol information. The -i switch signals the daemon to reload the kernel module symbols. The -I switch signals for a reload of both the static kernel symbols and the kernel module symbols.

-n
Avoid auto-backgrounding. This is needed especially if the klogd is started and controlled by init(8).

-o
Execute in 'one-shot' mode. This causes klogd to read and log all the messages that are found in the kernel message buffers. After a single read and log cycle the daemon exits.

-p
Enable paranoia. This option controls when klogd loads kernel module symbol information. Setting this switch causes klogd to load the kernel module symbol information whenever an Oops string is detected in the kernel message stream.

-s
Force klogd to use the system call interface to the kernel message buffers.

-k file
Use the specified file as the source of kernel symbol information.

-v
Print version and exit.

-x
Omits EIP translation and therefore doesn't read the System.map file.

-2
When symbols are expanded, print the line twice. Once with addresses converted to symbols, once with the raw text. This allows external programs such as ksymoops do their own processing on the original data.



#top syslog.conf


Strony man: syslog.conf

#top syslog-SELECTORS


The selector field itself again consists of two parts, a facility and a priority, separated by a period ("."). Both parts are case insensitive and can also be specified as decimal numbers, but don't do that, you have been warned. Both facilities and priorities are described in syslog(3). The names mentioned below correspond to the similar LOG_-values in /usr/include/syslog.h.

The facility is one of the following keywords: auth, authpriv, cron, daemon, kern, lpr, mail, mark, news, security (same as auth), syslog, user, uucp and local0 through local7. The keyword security should not be used anymore and mark is only for internal use and therefore should not be used in applications. Anyway, you may want to specify and redirect these messages here. The facility specifies the subsystem that produced the message, i.e. all mail programs log with the mail facility (LOG_MAIL) if they log using syslog.

The priority is one of the following keywords, in ascending order: debug, info, notice, warning, warn (same as warning), err, error (same as err), crit, alert, emerg, panic (same as emerg). The keywords error, warn and panic are deprecated and should not be used anymore. The priority defines the severity of the message

The behavior of the original BSD syslogd is that all messages of the specified priority and higher are logged according to the given action. This syslogd(8) behaves the same, but has some extensions.
In addition to the above mentioned names the syslogd(8) understands the following extensions: An asterisk (""*") stands for all facilities or all priorities, depending on where it is used (before or after the period). The keyword none stands for no priority of the given facility.

You can specify multiple facilities with the same priority pattern in one statement using the comma (",") operator. You may specify as much facilities as you want. Remember that only the facility part from such a statement is taken, a priority part would be skipped.

Multiple selectors may be specified for a single action using the semicolon (";") separator. Remember that each selector in the selector field is capable to overwrite the preceding ones. Using this behavior you can exclude some priorities from the pattern.

This syslogd(8) has a syntax extension to the original BSD source, that makes its use more intuitively. You may precede every priority with an equation sign ("=") to specify only this single priority and not any of the above. You may also (both is valid, too) precede the priority with an exclamation mark ("!") to ignore all that priorities, either exact this one or this and any higher priority. If you use both extensions than the exclamation mark must occur before the equation sign, just use it intuitively.



#top syslog-ACTIONS


The action field of a rule describes the abstract term "logfile". A "logfile" need not to be a real file, btw. The syslogd(8) provides the following actions.

Regular File
Typically messages are logged to real files. The file has to be specified with full pathname, beginning with a slash "/".

You may prefix each entry with the minus "-" sign to omit syncing the file after every logging. Note that you might lose information if the system crashes right behind a write attempt. Nevertheless this might give you back some performance, especially if you run programs that use logging in a very verbose manner.

Named Pipes
This version of syslogd(8) has support for logging output to named pipes (fifos). A fifo or named pipe can be used as a destination for log messages by prepending a pipe symbol ("|") to the name of the file. This is handy for debugging. Note that the fifo must be created with the mkfifo(1) command before syslogd(8) is started.

Terminal and Console
If the file you specified is a tty, special tty-handling is done, same with /dev/console.

Remote Machine
This syslogd(8) provides full remote logging, i.e. is able to send messages to a remote host running syslogd(8) and to receive messages from remote hosts. The remote host won't forward the message again, it will just log them locally. To forward messages to another host, prepend the hostname with the at sign ("@").

Using this feature you're able to control all syslog messages on one host, if all other machines will log remotely to that. This tears down administration needs.

List of Users
Usually critical messages are also directed to "root" on that machine. You can specify a list of users that shall get the message by simply writing the login. You may specify more than one user by separating them with commas (","). If they're logged in they get the message. Don't think a mail would be sent, that might be too late.

Everyone logged on
Emergency messages often go to all users currently online to notify them that something strange is happening with the system. To specify this wall(1)-feature use an asterisk ("*").



#top syslog-config


Zgodnie z dokumentacją należy zwrócić uwagę na: You may prefix each entry with the minus "-" sign to omit syncing the file after every logging. dzięki czemu można określić, czy zapis do logów ma odbywać się wraz z synchronizacją zapisu danych na dysk (co może obniżyć wydajność podsystemu dyskowego, ale gwarantuje mniejsze prawdopodobieństwo utraty danych) lub z pominięciem synchronizacji danych przy zapisie (co zwiększa wydajność podczas zapisu, ale wiąże się z ryzykiem utraty danych w przypadku awarii systemu lub zasialania).

Przedstawiony poniżej plik konfiguracyjny /etc/syslog.conf zawiera skonfigurowane wszystkie interesujące / przydatne źródła, należy uprzednio utworzyć niezbędne brakujące katalogi:
mkdir /var/log/mail
mkdir /var/log/crond
mkdir /var/log/daemon
mkdir /var/log/kernel
mkdir /var/log/lpr
mkdir /var/log/news

Po zainstalowaniu plik konfiguracyjny /etc/syslog.conf nie zawiera włączonych mechanizmów logowania wszystkich przydatnych / dostępnych źródeł. Poniżej przedstawiono plik konfiguracyjny zawierający skonfigurowane wszystkie interesujące / przydatne źródła:
# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.*                                                 /dev/console

# Log syslog
syslog.*                        -/var/log/syslog

# The authpriv file has restricted access.
authpriv.*                      /var/log/secure

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none                /var/log/messages

# Log all the mail messages in one place.
#mail.*                                                 -/var/log/maillog
# Mail logging
mail.*                          /var/log/mail/mail.log

# Log cron stuff
#cron.*                                                 /var/log/cron
# Cron logging
cron.*                          /var/log/crond/crond.log

# Daemon logging
daemon.*                        /var/log/daemon/daemon.log

# Kernel logging
kern.*                          /var/log/kernel/kernel.log

# Lpr logging
lpr.*                           /var/log/lpr/lpr.log

# News logging
news.*                          /var/log/news/news.log

# user messages
user.*                          -/var/log/user.log

# Everybody gets emergency messages
*.emerg                         *

# Save news errors of level crit and higher in a special file.
uucp,news.crit                  /var/log/spooler

# Save boot messages also to boot.log
local7.*                        /var/log/boot.log



#top /etc/sysconfig/rsyslog


Konfiguracja demona rsyslogd znajduje się w pliku konfiguracyjnym /etc/rsyslog.conf w przypadku zastosowania innej lokalizacji niezbędne jest przekazanie tej informacji demonowi w postaci argumentu -f /path/to/syslog-file.conf. Niniejszą informację należy umieścić w zmiennej SYSLOGD_OPTIONS zdefiniowanej w pliku /etc/sysconfig/rsyslog wczytywanym przez skrypt startowy demona. Dostępny po instalacji plik /etc/sysconfig/rsyslog wygląda analogicznie jak poniżej:
# Options for rsyslogd
# Syslogd options are deprecated since rsyslog v3.
# If you want to use them, switch to compatibility mode 2 by "-c 2"
# See rsyslogd(8) for more details
SYSLOGD_OPTIONS="-c 5"



#top rsyslogd


Strony man: rsyslogd - reliable and extended syslogd
Dokumentacja: www.rsyslog.com

SYNOPSIS
rsyslogd [ -4 ] [ -6 ] [ -A ] [ -d ] [ -f config file ] [ -i pid file ] [ -l hostlist ] [ -n ] [ -N level ] [ -q ] [ -Q ] [ -s domainlist ] [ -u userlevel ] [ -v ] [ -w ] [ -x ]

Poniżej przedstawiono argumenty, które można przekazać demonowi rsyslogd podczas uruchamiania by zmienić jego zachowanie:
OPTIONS
Note that in version 3 of rsyslog a number of command line options have been deprecated and replaced with config file directives. The -c option controls the backward compatibility mode in use.

-A
When sending UDP messages, there are potentially multiple paths to the target destination. By default, rsyslogd only sends to the first target it can successfully send to. If -A is given, messages are sent to all targets. This may improve reliability, but may also cause message duplication. This option should be enabled only if it is fully understood.

-4
Causes rsyslogd to listen to IPv4 addresses only. If neither -4 nor -6 is given, rsyslogd listens to all configured addresses of the system.

-6
Causes rsyslogd to listen to IPv6 addresses only. If neither -4 nor -6 is given, rsyslogd listens to all configured addresses of the system.

-c version
Selects the desired backward compatibility mode. It must always be the first option on the command line, as it influences processing of the other options. To use the rsyslog v3 native interface, specify -c3. To use compatibility mode, either do not use -c at all or use -c<version> where version is the rsyslog version that it shall be compatible with. Using -c0 tells rsyslog to be command-line compatible to sysklogd, which is the default if -c is not given. Please note that rsyslogd issues warning messages if the -c3 command line option is not given. This is to alert you that your are running in compatibility mode. Compatibility mode interferes with your rsyslog.conf commands and may cause some undesired side-effects. It is meant to be used with a plain old rsyslog.conf - if you use new features, things become messy. So the best advice is to work through this document, convert your options and config file and then use rsyslog in native mode. In order to aid you in this process, rsyslog logs every compatibility-mode config file directive it has generated. So you can simply copy them from your logfile and paste them to the config.

-d
Turns on debug mode. See the DEBUGGING section for more information.

-f config file
Specify an alternative configuration file instead of /etc/rsyslog.conf, which is the default.

-i pid file
Specify an alternative pid file instead of the default one. This option must be used if multiple instances of rsyslogd should run on a single machine.

-l hostlist
Specify a hostname that should be logged only with its simple hostname and not the fqdn. Multiple hosts may be specified using the colon (":") separator.

-n
Avoid auto-backgrounding. This is needed especially if the rsyslogd is started and controlled by init(8).

-N level
Do a coNfig check. Do NOT run in regular mode, just check configuration file correctness. This option is meant to verify a config file. To do so, run rsyslogd interactively in foreground, specifying -f <config-file> and -N level. The level argument modifies behaviour. Currently, 0 is the same as not specifying the -N option at all (so this makes limited sense) and 1 actually activates the code. Later, higher levels will mean more verbosity (this is a forward-compatibility option). rsyslogd is started and controlled by init(8).

-q add hostname if DNS fails during ACL processing
During ACL processing, hostnames are resolved to IP addresses for performance reasons. If DNS fails during that process, the hostname is added as wildcard text, which results in proper, but somewhat slower operation once DNS is up again.

-Q do not resolve hostnames during ACL processing
Do not resolve hostnames to IP addresses during ACL processing.

-s domainlist
Specify a domainname that should be stripped off before logging. Multiple domains may be specified using the colon (":") separator. Please be advised that no sub-domains may be specified but only entire domains. For example if -s north.de is specified and the host logging resolves to satu.infodrom.north.de no domain would be cut, you will have to specify two domains like: -s north.de:infodrom.north.de.

-u userlevel
This is a "catch all" option for some very seldomly-used user settings. The "userlevel" variable selects multiple things. Add the specific values to get the combined effect of them. A value of 1 prevents rsyslogd from parsing hostnames and tags inside messages. A value of 2 prevents rsyslogd from changing to the root directory. This is almost never a good idea in production use. This option was introduced in support of the internal testbed. To combine these two features, use a userlevel of 3 (1+2). Whenever you use an -u option, make sure you really understand what you do and why you do it.

-v
Print version and exit.

-w
Suppress warnings issued when messages are received from non-authorized machines (those, that are in no AllowedSender list).

-x
Disable DNS for remote messages.



#top rsyslog.conf


Strony man: rsyslog.conf

#top rsyslog-SELECTORS


The selector field itself again consists of two parts, a facility and a priority, separated by a period ("."). Both parts are case insensitive and can also be specified as decimal numbers, but don't do that, you have been warned. Both facilities and priorities are described in syslog(3). The names mentioned below correspond to the similar LOG_-values in /usr/include/syslog.h.

The facility is one of the following keywords: auth, authpriv, cron, daemon, kern, lpr, mail, mark, news, security (same as auth), syslog, user, uucp and local0 through local7. The keyword security should not be used anymore and mark is only for internal use and therefore should not be used in applications. Anyway, you may want to specify and redirect these messages here. The facility specifies the subsystem that produced the message, i.e. all mail programs log with the mail facility (LOG_MAIL) if they log using syslog.

The priority is one of the following keywords, in ascending order: debug, info, notice, warning, warn (same as warning), err, error (same as err), crit, alert, emerg, panic (same as emerg). The keywords error, warn and panic are deprecated and should not be used anymore. The priority defines the severity of the message.

The behavior of the original BSD syslogd is that all messages of the specified priority and higher are logged according to the given action. Rsyslogd behaves the same, but has some extensions.

In addition to the above mentioned names the rsyslogd(8) understands the following extensions: An asterisk ("*") stands for all facilities or all priorities, depending on where it is used (before or after the period). The keyword none stands for no priority of the given facility.

You can specify multiple facilities with the same priority pattern in one statement using the comma (",") operator. You may specify as much facilities as you want. Remember that only the facility part from such a statement is taken, a priority part would be skipped.

Multiple selectors may be specified for a single action using the semicolon (";") separator. Remember that each selector in the selector field is capable to overwrite the preceding ones. Using this behavior you can exclude some priorities from the pattern.

Rsyslogd has a syntax extension to the original BSD source, that makes its use more intuitively. You may precede every priority with an equation sign ("=") to specify only this single priority and not any of the above. You may also (both is valid, too) precede the priority with an exclamation mark ("!") to ignore all that priorities, either exact this one or this and any higher priority. If you use both extensions than the exclamation mark must occur before the equation sign, just use it intuitively.



#top rsyslog-ACTIONS


The action field of a rule describes what to do with the message. In general, message content is written to a kind of "logfile". But also other actions might be done, like writing to a database table or forwarding to another host.

Regular file
Typically messages are logged to real files. The file has to be specified with full pathname, beginning with a slash ('/').

Example:
*.* /var/log/traditionalfile.log;RSYSLOG_Traditional-Format # log to a file in the traditional format

Note: if you would like to use high-precision timestamps in your log files, just remove the ";RSYSLOG_TraditionalFormat". That will select the default template, which, if not changed, uses RFC 3339 timestamps.

Example:
*.* /var/log/file.log # log to a file with RFC3339 timestamps

Named pipes
This version of rsyslogd(8) has support for logging output to named pipes (fifos). A fifo or named pipe can be used as a destination for log messages by prepending a pipe symbol ('|') to the name of the file. This is handy for debugging. Note that the fifo must be created with the mkfifo(1) command before rsyslogd(8) is started.

Terminal and console
If the file you specified is a tty, special tty-handling is done, same with /dev/console.

Remote machine
There are three ways to forward message: the traditional UDP transport, which is extremely lossy but standard, the plain TCP based transport which loses messages only during certain situations but is widely available and the RELP transport which does not lose messages but is currently available only as part of rsyslogd 3.15.0 and above.

To forward messages to another host via UDP, prepend the hostname with the at sign ("@"). To forward it via plain tcp, prepend two at signs ("@@"). To forward via RELP, prepend the string ":omrelp:" in front of the hostname.

Example:
*.* @192.168.0.1

In the example above, messages are forwarded via UDP to the machine 192.168.0.1, the destination port defaults to 514. Due to the nature of UDP, you will probably lose some messages in transit. If you expect high traffic volume, you can expect to lose a quite noticeable number of messages (the higher the traffic, the more likely and severe is message loss).

If you would like to prevent message loss, use RELP:
*.* :omrelp:192.168.0.1:2514

Note that a port number was given as there is no standard port for relp.

Keep in mind that you need to load the correct input and output plugins (see "Modules" above).

Please note that rsyslogd offers a variety of options in regarding to remote forwarding. For full details, please see the html documentation.

List of users
Usually critical messages are also directed to "root" on that machine. You can specify a list of users that shall get the message by simply writing the login. You may specify more than one user by separating them with commas (','). If they're logged in they get the message. Don't think a mail would be sent, that might be too late.

Everyone logged on
Emergency messages often go to all users currently online to notify them that something strange is happening with the system. To specify this wall(1)-feature use an asterisk ('*').

Database table
This allows logging of the message to a database table. By default, a MonitorWare-compatible schema is required for this to work. You can create that schema with the createDB.SQL file that came with the rsyslog package. You can also use any other schema of your liking - you just need to define a proper template and assign this template to the action.

See the html documentation for further details on database logging.

Discard
If the discard action is carried out, the received message is immediately discarded. Discard can be highly effective if you want to filter out some annoying messages that otherwise would fill your log files. To do that, place the discard actions early in your log files. This often plays well with property-based filters, giving you great freedom in specifying what you do not want.

Discard is just the single tilde character with no further parameters.

Example:
*.* ~ # discards everything.

Output channel
Binds an output channel definition (see there for details) to this action. Output channel actions must start with a $-sign, e.g. if you would like to bind your output channel definition "mychannel" to the action, use "$mychannel". Output channels support template definitions like all all other actions.

Shell execute
This executes a program in a subshell. The program is passed the template-generated message as the only command line parameter. Rsyslog waits until the program terminates and only then continues to run.

Example:
^program-to-execute;template

The program-to-execute can be any valid executable. It receives the template string as a single parameter (argv[1]).



#top rsyslog-config


Zgodnie z dokumentacją należy zwrócić uwagę na: You may prefix each entry with the minus "-" sign to omit syncing the file after every logging. dzięki czemu można określić, czy zapis do logów ma odbywać się wraz z synchronizacją zapisu danych na dysk (co może obniżyć wydajność podsystemu dyskowego, ale gwarantuje mniejsze prawdopodobieństwo utraty danych) lub z pominięciem synchronizacji danych przy zapisie (co zwiększa wydajność podczas zapisu, ale wiąże się z ryzykiem utraty danych w przypadku awarii systemu lub zasialania).

Przedstawiony poniżej plik konfiguracyjny /etc/rsyslog.conf zawiera skonfigurowane wszystkie interesujące / przydatne źródła, należy uprzednio utworzyć niezbędne brakujące katalogi:
mkdir /var/log/mail
mkdir /var/log/crond
mkdir /var/log/daemon
mkdir /var/log/kernel
mkdir /var/log/lpr
mkdir /var/log/news

Po zainstalowaniu plik konfiguracyjny /etc/rsyslog.conf nie zawiera włączonych mechanizmów logowania wszystkich przydatnych / dostępnych źródeł. Poniżej przedstawiono plik konfiguracyjny zawierający skonfigurowane wszystkie interesujące / przydatne dostępne źródła:
#rsyslog v3 config file

# if you experience problems, check
# http://www.rsyslog.com/troubleshoot for assistance

#### MODULES ####

$ModLoad imuxsock.so    # provides support for local system logging (e.g. via
logger command)
$ModLoad imklog.so      # provides kernel logging support (previously done by
rklogd)
#$ModLoad immark.so     # provides --MARK-- message capability

# Provides UDP syslog reception
#$ModLoad imudp.so
#$UDPServerRun 514

# Provides TCP syslog reception
#$ModLoad imtcp.so
#$InputTCPServerRun 514


#### GLOBAL DIRECTIVES ####

# Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

# File syncing capability is disabled by default. This feature is usually not
# required,
# not useful and an extreme performance hit
#$ActionFileEnableSync on


#### RULES ####

# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.*                         /dev/console

# Log syslog
syslog.*                        -/var/log/syslog

# The authpriv file has restricted access.
authpriv.*                      /var/log/secure

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none                /var/log/messages

# Log all the mail messages in one place.
#mail.*                         -/var/log/maillog
# Mail logging
mail.*                          /var/log/mail/mail.log

# Log cron stuff
#cron.*                                                  /var/log/cron
# Cron logging
cron.*                          /var/log/crond/crond.log

# Daemon logging
daemon.*                        /var/log/daemon/daemon.log

# Kernel logging
kern.*                          /var/log/kernel/kernel.log

# Lpr logging
lpr.*                           /var/log/lpr/lpr.log

# News logging
news.*                          /var/log/news/news.log

# user messages
user.*                          -/var/log/user.log

# Everybody gets emergency messages
*.emerg                         *

# Save news errors of level crit and higher in a special file.
uucp,news.crit                  /var/log/spooler

# Save boot messages also to boot.log
local7.*                        /var/log/boot.log



# ### begin forwarding rule ###
# The statement between the begin ... end define a SINGLE forwarding
# rule. They belong together, do NOT split them. If you create multiple
# forwarding rules, duplicate the whole block!
# Remote Logging (we use TCP for reliable delivery)
#
# An on-disk queue is created for this action. If the remote host is
# down, messages are spooled to disk and sent when it is up again.
#$WorkDirectory /var/spppl/rsyslog # where to place spool files
#$ActionQueueFileName fwdRule1 # unique name prefix for spool files
#$ActionQueueMaxDiskSpace 1g   # 1gb space limit (use as much as possible)
#$ActionQueueSaveOnShutdown on # save messages to disk on shutdown
#$ActionQueueType LinkedList   # run asynchronously
#$ActionResumeRetryCount -1    # infinite retries if host is down
# remote host is: name/ip:port, e.g. 192.168.0.1:514, port optional
#*.* @@remote-host:514
# ### end of the forwarding rule ###



#top remote logging


Włączenie odbierania logów ze zdalnych maszyn / hostów w demonach syslog i rsyslog (nasłuchiwanie na UDP/TCP inet socket (adres IP / port)) konfiguruje się nieco odmiennie.

syslogd
Włączenie nasłuchiwania na UDP socket i odbierania logów ze zdalnych maszyn w demonie syslog konfiguruje się poprzez uruchomienie demona syslog z argumentem -r (enables logging from remote machines) w zmiennej SYSLOGD_OPTIONS zdefiniowanej w pliku /etc/sysconfig/syslog wczytywanym przez skrypt startowy demona. Z powodu wczytywania pliku /etc/sysconfig/syslog przy starcie demona syslogd niniejsza zmiana wymaga restartu demona syslogd. Przydatną opcją w przypadku stosowania odbierania logów ze zdalnych maszyn / hostów jest wyłączenie rozwiązywania adresów IP na nazwy podczas odbierania informacji. Realizowane jest to poprzez uruchomienie demona syslog z argumentem -x (disables DNS lookups on messages recieved with -r) umieszczonym w zmiennej SYSLOGD_OPTIONS zdefiniowanej w pliku /etc/sysconfig/syslog wczytywanym przez skrypt startowy demona (również wymaga restartu demona syslogd).
Po wprowadzoniu zmian w pliku /etc/sysconfig/syslog wczytywanym przez skrypt startowy demona fragment pliku powinien wyglądać analogicznie jak poniżej:
# Options to syslogd
# -m 0 disables 'MARK' messages.
# -r enables logging from remote machines
# -x disables DNS lookups on messages recieved with -r
# See syslogd(8) for more details
SYSLOGD_OPTIONS="-m 0 -r -x"

rsyslogd
Włączenie nasłuchiwania na UDP socket i odbierania logów ze zdalnych maszyn w demonie rsyslog konfiguruje się poprzez aktywację opcji (odkomentowanie) $ModLoad imudp.so oraz $UDPServerRun 514 w pliku konfiguracyjnym /etc/rsyslog.conf. Dodatkowo demon rsyslog obsługuje protokół TCP. Włączenie nasłuchiwania na TCP socket i odbierania logów ze zdalnych maszyn w demonie rsyslog konfiguruje się poprzez aktywację opcji (odkomentowanie) $ModLoad imtcp.so oraz $InputTCPServerRun 514 w pliku konfiguracyjnym /etc/rsyslog.conf. Dzieki temu nie jest niezbędny restart demona rsyslogd, wystarczy ponowne wczytanie konfiguracji demona (reload). Dodatkowo w demonie rsyslogd dostępne są alternatywne opcje $ModLoad imtcp.so i $InputTCPServerRun 514 włączające nasłuchiwanie na TCP socket i odbieranie logów ze zdalnych maszyn po protokole połączeniowym gwarantującym niezawodne dostarczenie informacji.
Po wprowadzoniu zmian w pliku konfiguracyjnym demona fragment pliku /etc/rsyslog.conf z odkomentowanymi opcjami powinien wyglądać analogicznie jak poniżej:
# Provides UDP syslog reception
$ModLoad imudp.so
$UDPServerRun 514

# Provides TCP syslog reception
$ModLoad imtcp
$InputTCPServerRun 514



Włączenie wysyłania logów na zdalny serwer logów w demonach syslog i rsyslog konfiguruje się bardzo podobnie. Aby włączyć wysyłanie logów na zdalny serwer należy nazwę lub adres IP serwera logów poprzedzić znakiem @, alternatywnie zamiast ścieżki do pliku z logiem lub dodatkowo. W ten sposób, poprzez poprzedzenie nazwy lub adresu IP znakiem @ logi wysyłane są poprzez sieć z użyciem protokołu UDP. Demon rsyslog pozwala na wysyłanie logów poprzez sieć z użyciem protokołu TCP, aby wysyłanie logów poprzez sieć realizowane było z użyciem protokołu TCP należy nazwę lub adres IP poprzedzić dwoma znakami @@.
Poniżej przedstawiono konfigurację logowania informacji związanych z autoryzacją zarówno do lokalnego pliku /var/log/secure jak również do serwera logów o nazwie domenowej @cen05.xen.wbcd.pl z użyciem protokołu UDP oraz do serwera logów o nazwie domenowej @@cen06dev.xen.wbcd.pl z użyciem protokołu TCP:
# The authpriv file has restricted access.
authpriv.*                      /var/log/secure
authpriv.*                      @cen05.xen.wbcd.pl
# TCP protocol available only in rsyslog 4.* and higher
authpriv.*                      @@cen06dev.xen.wbcd.pl



#top sys/syslog.h


Logowanie informacji za pośrednictwem demona syslogd zaimplementowane jest w standardowej bibliotece systemowej, dzięki czemu aplikacje w dosyć łatwy sposób mogą zapisywać informacje do plików z logami bez konieczności posiadania uprawnień do plików (pliki otwarte są i zapisywane przez demona syslogd działającego najczęściej z uprawnieniami superużytkonika (root)).
Aplikacja musi dołączać dyrektywą include plik nagłówkowy sys/syslog.h dostępny po zainstalowaniu pakietu headers biblioteki systemowej.



#top options


Dokumentacja online: pubs.opengroup.org

Deklaracja stałych LOG_*** określających dozwolone wartości argumentu __option funkcji openlog() znajduje się w pliku nagłówkowym sys:syslog.h.
Deklaracja stałych LOG_*** jest następująca:
/*
 * Option flags for openlog.
 *
 * LOG_ODELAY no longer does anything.
 * LOG_NDELAY is the inverse of what it used to be.
 */
#define LOG_PID         0x01    /* log the pid with each message */
#define LOG_CONS        0x02    /* log on the console if errors in sending */
#define LOG_ODELAY      0x04    /* delay open until first syslog() (default) */
#define LOG_NDELAY      0x08    /* don't delay open */
#define LOG_NOWAIT      0x10    /* don't wait for console forks: DEPRECATED */
#define LOG_PERROR      0x20    /* log to stderr as well */

The option argument to openlog() is an OR of any of these:
LOG_CONS Write directly to system console if there is an error while sending to system logger.
LOG_NDELAY Open the connection immediately (normally, the connection is opened when the first message is logged).
LOG_NOWAIT Don't wait for child processes that may have been created while logging the message. (The GNU C library does not create a child process, so this option has no effect on Linux.)
LOG_ODELAY The converse of LOG_NDELAY; opening of the connection is delayed until syslog() is called. (This is the default, and need not be specified.)
LOG_PERROR (Not in POSIX.1-2001 or POSIX.1-2008.) Print to stderr as well.
LOG_PID Include PID with each message.



#top facilities


Dokumentacja online: pubs.opengroup.org

Deklaracja stałych LOG_*** określających dozwolone wartości źródeł logowanych informacji przekazywanych w argumencie __facility funkcji openlog() znajduje się w pliku nagłówkowym sys:syslog.h.
Deklaracja stałych LOG_*** jest następująca:
/* facility codes */
#define LOG_KERN        (0<<3)  /* kernel messages */
#define LOG_USER        (1<<3)  /* random user-level messages */
#define LOG_MAIL        (2<<3)  /* mail system */
#define LOG_DAEMON      (3<<3)  /* system daemons */
#define LOG_AUTH        (4<<3)  /* security/authorization messages */
#define LOG_SYSLOG      (5<<3)  /* messages generated internally by syslogd */
#define LOG_LPR         (6<<3)  /* line printer subsystem */
#define LOG_NEWS        (7<<3)  /* network news subsystem */
#define LOG_UUCP        (8<<3)  /* UUCP subsystem */
#define LOG_CRON        (9<<3)  /* clock daemon */
#define LOG_AUTHPRIV    (10<<3) /* security/authorization messages (private) */
#define LOG_FTP         (11<<3) /* ftp daemon */

        /* other codes through 15 reserved for system use */
#define LOG_LOCAL0      (16<<3) /* reserved for local use */
#define LOG_LOCAL1      (17<<3) /* reserved for local use */
#define LOG_LOCAL2      (18<<3) /* reserved for local use */
#define LOG_LOCAL3      (19<<3) /* reserved for local use */
#define LOG_LOCAL4      (20<<3) /* reserved for local use */
#define LOG_LOCAL5      (21<<3) /* reserved for local use */
#define LOG_LOCAL6      (22<<3) /* reserved for local use */
#define LOG_LOCAL7      (23<<3) /* reserved for local use */

The facility argument is used to specify what type of program is logging the message. This lets the configuration file specify that messages from different facilities will be handled differently.
LOG_AUTH security/authorization messages
LOG_AUTHPRIV security/authorization messages (private)
LOG_CRON clock daemon (cron and at)
LOG_DAEMON system daemons without separate facility value
LOG_FTP ftp daemon
LOG_KERN kernel messages (these can't be generated from user processes)
LOG_LOCAL0 through LOG_LOCAL7 reserved for local use
LOG_LPR line printer subsystem
LOG_MAIL mail subsystem
LOG_NEWS USENET news subsystem
LOG_SYSLOG messages generated internally by syslogd(8)
LOG_USER (default) generic user-level messages
LOG_UUCP UUCP subsystem



#top priorities


Dokumentacja online: pubs.opengroup.org

Deklaracja stałych LOG_*** określających dozwolone wartości priorytetów logowanych informacji przekazywanych w argumencie __pri funkcji syslog() znajduje się w pliku nagłówkowym sys:syslog.h.
Deklaracja stałych LOG_*** jest następująca:
/*
 * priorities/facilities are encoded into a single 32-bit quantity, where the
 * bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
 * (0-big number).  Both the priorities and the facilities map roughly
 * one-to-one to strings in the syslogd(8) source code.  This mapping is
 * included in this file.
 *
 * priorities (these are ordered)
 */
#define LOG_EMERG       0       /* system is unusable */
#define LOG_ALERT       1       /* action must be taken immediately */
#define LOG_CRIT        2       /* critical conditions */
#define LOG_ERR         3       /* error conditions */
#define LOG_WARNING     4       /* warning conditions */
#define LOG_NOTICE      5       /* normal but significant condition */
#define LOG_INFO        6       /* informational */
#define LOG_DEBUG       7       /* debug-level messages */

This determines the importance of the message. The levels are, in order of decreasing importance:
LOG_EMERG system is unusable
LOG_ALERT action must be taken immediately
LOG_CRIT critical conditions
LOG_ERR error conditions
LOG_WARNING warning conditions
LOG_NOTICE normal, but significant, condition
LOG_INFO informational message
LOG_DEBUG debug-level message
The function setlogmask(3) can be used to restrict logging to specified levels only.



#top openlog


Dokumentacja online: pubs.opengroup.org

Aby zainicjalizować logowanie informacji w bibliotece systemowej aplikacja musi wywołać funkcję openlog(). Funkcja openlog() zdefiniowana jest następująco:
/* Open connection to system logger.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern void openlog (__const char *__ident, int __option, int __facility);

Argumenty:
const char *__ident - łańcuch znaków którym zostanie poprzedzona logowana informacja, stanowiąca swego rodzaju idetyfikator źródła pochodzenia informacji (najczęsciej jest to nazwa pozwalająca zidentyfikować aplikację umieszczającą informację w logach),
int __option - dodatkowe parametry, które zostaną dodane do identyfikatora przekazanego a w argumencie __ident źródła pochodzenia informacji (np: PID procesu). Plik nagłówkowy sys/syslog.h definiuje następujące stałe, które jako suma logiczna mogą być przekazane do funkcji modyfikując jej zachowanie:
int __facility - źródło pochodzenia logowanych informacji. Plik nagłówkowy sys/syslog.h definiuje następujące stałe, które mogą być przekazane do funkcji określając źródło pochodzenia logowanych informacji:
Zwracana wartość:
Funkcja openlog() nie zwraca żadnej wartości.


#top setlogmask


Dokumentacja online: pubs.opengroup.org

/* Set the log mask level.  */
extern int setlogmask (int __mask) __THROW;

Argumenty:
int __mask -
Zwracana wartość:
int -



#top syslog


Dokumentacja online: pubs.opengroup.org

Logowanie informacji realizowane jest poprzez wywołanie funkcji syslog(). Funkcja syslog() zdefiniowana jest następująco:
/* Generate a log message using FMT string and option arguments.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern void syslog (int __pri, __const char *__fmt, ...)
     __attribute__ ((__format__ (__printf__, 2, 3)));

Argumenty:
int __pri - priorytet logowanych informacji. Plik nagłówkowy sys/syslog.h definiuje następujące stałe, które mogą być przekazane do funkcji określając priorytet logowanych informacji:
const char *__fmt - łańcuch znaków formatujący logowaną wiadomość (łańcuch znaków analogiczny do funkcji printf).
... - argumenty skorelowane z formatem przekazanym w argumencie __fmt.

Zwracana wartość:
Funkcja syslog() nie zwraca żadnej wartości.


#top closelog


Dokumentacja online: pubs.opengroup.org

Przed końcem pracy aplikacja powinna wywołać funkcję closelog() aby dokonać procesu odwrotnego do inicjalizacji logowania informacji w bibliotece systemowej. Funkcja closelog() zdefiniowana jest następująco:
/* Close descriptor used to write to system logger.

   This function is a possible cancellation point and therefore not
   marked with __THROW.  */
extern void closelog (void);

Argumenty:
Funkcja closelog() nie przyjmuje żadnej wartości.

Zwracana wartość:
Funkcja closelog() nie zwraca żadnej wartości.



Example:
SELECT ALL
#include <sys/syslog.h>
int main() {
	openlog("syslogprint", LOG_PID|LOG_CONS, LOG_LOCAL2);
	syslog(LOG_INFO, "A different kind of Hello world ... ");
	closelog();
	return 0;
}









Zmodyfikowany ostatnio: 2016/05/23 10:26:39 (7 lat temu), textsize: 57,2 kB, htmlsize: 73,5 kB

Zapraszam do komentowania, zgłaszania sugestii, propozycji, własnych przykładów, ...
Dodaj komentarzKomentarze użytkowników