Score:2

Getting Syslog to log to both syslog and custom log file

cn flag

In syslog (Raspbian rsyslog swVersion="8.1901.0"),

I am trying to match / filter a system msg containing a specific string BOTH to /var/log/syslog (default) AND to a custom separate log file, i.e.: /var/log/nut.log.

I have been able to achieve the by placing the following filter lines in /etc/rsyslog.conf:

# NUT logging: Include USB msgs since montoring UPS via only USB
:msg,contains,"USB" /var/log/nut.log
& stop
:msg,contains,"nut-" /var/log/nut.log
& stop

The & stop is needed to halt the filters once a match is made. I believe the preferred method is to place this in a dedicated file, i.e.: /etc/rsyslog.d/0-nut.conf

But, when I do that, the filters stop logging to /var/log/syslog, and exclusively log to /var/log/nut.log... ?

Is there a different way to do this?

Thx!

meuh avatar
in flag
Do you need the `& stop`? Do you have msgs with both "USB" and "nut-" that will get logged twice?
DJacobson avatar
cn flag
@meuh That was indeed my problem and your answer below was perfect.
Score:0
in flag

The $IncludeConfig or include() directive in rsyslog.conf appears before most of the standard rules, including the one that writes messages to /var/log/syslog. If you add your rules after the other rules in this file, then the nut messages will have already been written to syslog before it is also matched and written to nut.log.

If instead you put your rules in a separate file, the message will be written to nut.log, then the stop will skip the later rules. The answer is not to use stop.

If the problem is that a message might contain both "USB" and "nut-", and so be written twice to nut.log, then you need to use a more sophisticated syntax.

The legacy syntax was replaced by RainerScript a long time ago. It means you can write filters like:

if ($msg contains "USB" or $msg contains "nut-") then {
   action(type="omfile" file="/var/log/nut.log")
}

This does not need to prevent further processing of the message.

DJacobson avatar
cn flag
Thank you. I learned a lot about the order of Rsyslog processing in your concise answer. I was indeed trying to avoid duplicated log msgs.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.