Rsyslog documentation

Обработка сообщений

  • Все сообщения приходят из Input(им может быть много) и попадают на обработку в привязанный к нему RuleSet. Если это явно не задано, то сообщения попадут в RuleSet по-умолчанию. Все директивы обработки сообщений, не вынесенные в отдельные RuleSet-блоки, относятся именно к нему. В частности, к нему относятся все директивы из традиционного формата конфигов:
  • к Input привязан список парсеров для разбора сообщения. Если явно не задано, будет использоваться список парсеров для разбора традиционного формата syslog
  • Парсер выделяет из сообщения свойства. Самые используемые:
    • — сообщение
    • — сообщение целиком до обработки парсером
    • , — DNS имя и IP адрес хоста-отправителя
    • , — facility в числовой и текстовой форме
    • , — то же для severity
    • — время из сообщения
    • — поле TAG
    • — поле TAG с отрезанным id процесса: ->
  • RuleSet содержит список правил, правило состоит из фильтра и привязанных к нему одного или нескольких Actions
  • Правила применяются последовательно к сообщению, попавшему в RuleSet, на первом сработавшем правиле сообщение не останавливается
  • Чтобы остановить обработку сообщения, можно использовать специальное discard action: или в легаси-формате.
  • Как правило, Action использует модуль вывода(«om…») или модуль изменения сообщения(«mm…»). Вот некоторые из них:

Механизм

Стандартом предусматривается, что источники формируют простые текстовые сообщения о происходящих в них событиях и передают их на обработку серверу Syslog (называемому «syslogd», «syslog daemon», либо же, «syslog server»), используя один из сетевых протоколов семейства IP (UDP или TCP). Формирование сообщений о событиях и их передача происходит по определённым правилам, называемым протоколом Syslog. Как правило сообщение имеет небольшой размер (до 1024 байт) и отсылается в открытом виде. Тем не менее, при использовании специальных средств (таких, как Stunnel, sslio или sslwrap), возможно шифрование сообщений и отправка их по SSL/TLS.

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

Также серверы Syslog, как правило, могут не только регистрировать сообщения, но и пересылать их другим серверам Syslog, основываясь на уровне важности сообщения (Severity) и категории сформировавшего сообщение субъекта (Facility), что позволяет организовать, например, иерархическую систему хранилищ. А это может помочь, например, снизить время реакции персонала на критические события

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

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

Conclusion

Syslog tracking via a powerful Syslog server can save any network administrator an obscene amount of time and effort.

Every bit of data, whether SNMP or Syslog, that can be requested, aggregated, and analyzed is another potential piece of a puzzle that can trigger alerts or notifications and quickly bring human attention to the problem as soon as possible, or even fire off predefined scripts or programs to alleviate, or at least slow down, oncoming issues.

The flexibility of these programs are a superb way for admins to leverage monitoring to their advantage with the goal of maximum uptime and stability.

Much of this information can be seen on any one system or device, but even a small network with a few dozen devices would be totally unreasonable to monitor one by one – having it centralized, automated, and closely monitored is invaluable!

Config Statements

# this is the simplest forwarding action:
*.* action(type="omfwd" target="192.0.2.1" port="10514" protocol="tcp")
# it is equivalent to the following obsolete legacy format line:
*.* @@192.0.2.1:10514 # do NOT use this any longer!
# Note: if the remote system is unreachable, processing will
# block here and discard messages after a while

# so a better use is
*.*  action(type="omfwd" target="192.0.2.2" port="10514" protocol="tcp"
            action.resumeRetryCount="100"
            queue.type="linkedList" queue.size="10000")
# this will de-couple the sending from the other logging actions,
# and prevent delays when the remote system is not reachable. Also,
# it will try to connect 100 times before it discards messages as
# undeliverable.
# the rest below is more or less a plain vanilla rsyslog.conf as 
# many distros ship it - it's more for your reference...
# 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
# The authpriv file has restricted access.
authpriv.*                                    /var/log/secure
# Log all the mail messages in one place.
mail.*                                        /var/log/maillog
# Log cron stuff
cron.*                                        /var/log/cron
# Everybody gets emergency messages
*.emerg                                       :omusrmsg:*
# 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

Examples¶

*.* /var/log/file1 # the traditional way
if $msg contains 'error' then /var/log/errlog # the expression-based way

Right now, you need to specify numerical values if you would like to
check for facilities and severity. These can be found in RFC 5424.
If you don’t like that,
you can of course also use the textual property — just be sure to use
the right one. As expression support is enhanced, this will change. For
example, if you would like to filter on message that have facility
local0, start with “DEVNAME” and have either “error1” or “error0” in
their message content, you could use the following filter:

if $syslogfacility-text == 'local0' and $msg startswith 'DEVNAME' and ($msg contains 'error1' or $msg contains 'error0') then /var/log/somelog

Please note that the above must all be on one line! And if you would
like to store all messages except those that contain “error1” or
“error0”, you just need to add a “not”:

if $syslogfacility-text == 'local0' and $msg startswith 'DEVNAME' and not ($msg contains 'error1' or $msg contains 'error0') then /var/log/somelog

If you would like to do case-insensitive comparisons, use “contains_i”
instead of “contains” and “startswith_i” instead of “startswith”.
Note that regular expressions are currently NOT supported in
expression-based filters. These will be added later when function
support is added to the expression engine (the reason is that regular
expressions will be a separate loadable module, which requires some more
prerequisites before it can be implemented).

See also

Help with configuring/using :

  • Mailing list — best route for general questions
  • GitHub: rsyslog source project — detailed questions, reporting issues
    that are believed to be bugs with
  • Stack Exchange (View, Ask)
    — experimental support from rsyslog community

What does “To bind to a Ruleset” mean?¶

This term is used in the same sense as “to bind an IP address to an
interface”: it means that a specific input, or part of an input (like a
tcp listener) will use a specific ruleset to “pass its messages to”. So
when a new message arrives, it will be processed via the bound ruleset.
Rules from all other rulesets are irrelevant and will never be processed.

This makes multiple rulesets very handy to process local and remote
message via separate means: bind the respective receivers to different
rule sets, and you do not need to separate the messages by any other
method.

Binding to rulesets is input-specific. For imtcp, this is done via the

input(type="imptcp" port="514" ruleset="rulesetname")

Warning

There is problem caused by the »/proc/kmsg» implementation of the Linux kernel, namely, when two parallel processes open and try to read from the »/proc/kmsg» file.

This special file is the userspace interface for collecting kernel log messages. If there are multiple processes reading »/proc/kmsg», a race condition occurs and the process which loses the race essentially deadlocks until the next kernel message is generated, when a new race condition occurs.

If the system logger is blocked and is not processing userspace messages, slowly all system daemons stall while waiting for the system logger to become available again. This includes crucial system components like »’sshd»’ or the application handling system logins.

There are two alternative solutions for processing kernel messages on Linux systems:

  • using »’klogd»’ from the sysklogd package
  • reading »/proc/kmsg» from syslog-ng natively, without using the »’klogd»’ daemon

The second method is recommended.

The solution to this problem is to avoid running multiple userspace components that touch »/proc/kmsg». If you configure syslog-ng to read kernel messages, ensure that »’klogd»’ is not running. If you want to run »’klogd»’, ensure that »’syslog-ng»’ does not read »/proc/kmsg».

Running syslog-ng chrooted

Start syslog-ng using the »—chroot» command-line parameter. For example: »’syslog-ng —chroot /var/chroot»’.

before v3.0

The syslog-ng application initializes its configuration before the changing the root (e.g., the local UNIX domain socket »/dev/log» is opened before chrooting).

Note that it is not possible to reload the syslog-ng configuration after chrooting, thus you will need to use restart, or bind-mount the »/dev» directory into the chroot.

from v3.0

The syslog-ng application first changes the root and initializes its configuration file and opens files only afterward.

The Intention¶

Whenever two systems talk over a network, something can go wrong. For
example, the communications link may go down, or a client or server may
abort. Even in regular cases, the server may be offline for a short
period of time because of routine maintenance.

A logging system should be capable of avoiding message loss in
situations where the server is not reachable. To do so, unsent data
needs to be buffered at the client while the server is offline. Then,
once the server is up again, this data is to be sent.

This can easily be accomplished by rsyslog. In rsyslog, every action runs
on its own queue and each queue can be set to buffer data if the action
is not ready. Of course, you must be able to detect that “the action is
not ready”, which means the remote server is offline. This can be
detected with plain TCP syslog and RELP, but not with UDP. So you need
to use either of the two. In this howto, we use plain TCP syslog.

Please note that we are using rsyslog-specific features. The are
required on the client, but not on the server. So the client system must
run rsyslog (at least version 3.12.0), while on the server another
syslogd may be running, as long as it supports plain tcp syslog.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector