How to redirect specific log messages to separate log file using rsyslog in Linux

In my earlier articles I had shared the steps to transfer the rsyslog messages to a different host with and without TLS certificates. The difference is that with TLS certificates the transfer of log messages will be more secure.

Starting from Red Hat Enterprise Linux 7 that have migrated to rsyslog from traditional syslog hence there are multiple syntax changes in terms how syslog works.

Below steps have been validate on Red Hat Enterprise Linux 7

Suppose my syslog file is getting filled with multiple unwanted messages which I want to keep but not in syslog, may be some separate file so that the syslog has only important messages which are used day to day and to avoid frequent log rotation of the syslog.

For the sake of this example in Red Hat 7. below messages seems to fill up syslog
Jun 27 08:00:01 Ban17-inst01-a systemd: Starting Session 2213 of user root.
Jun 27 08:01:01 Ban17-inst01-a systemd: Started Session 2215 of user root.
Jun 27 08:01:01 Ban17-inst01-a systemd: Starting Session 2215 of user root.
Jun 27 08:05:01 Ban17-inst01-a systemd: Started Session 2216 of user root.
Jun 27 08:05:01 Ban17-inst01-a systemd: Starting Session 2216 of user root.
Jun 27 08:05:01 Ban17-inst01-a systemd: Started Session 2217 of user root.
Jun 27 08:05:01 Ban17-inst01-a systemd: Starting Session 2217 of user root.
Jun 27 08:10:01 Ban17-inst01-a systemd: Started Session 2218 of user root.
Jun 27 08:10:01 Ban17-inst01-a systemd: Starting Session 2218 of user root.
Jun 27 08:10:01 Ban17-inst01-a systemd: Started Session 2219 of user root.
I want to redirect all of these log messages to a separate file.

Create separate configuration file inside /etc/rsyslog.d

NOTE: By default all the configuration file inside /etc/rsyslog.d is considered by rsyslog.conf
You can validate this by looking for this entry inside /etc/rsyslog.conf
# Include all config files in /etc/rsyslog.d/
$IncludeConfig   /etc/rsyslog.d/*

# touch /etc/rsyslog.d/rsyslog_loginauth.conf

# vim /etc/rsyslog.d/rsyslog_loginauth.conf
if $programname == "systemd" and ($msg contains "Starting Session" or $msg contains "Started Session" or $msg contains "Created slice" or $msg contains "Starting user-") then /var/log/login_auth
& stop
Next restart the rsyslog service
# systemctl restart rsyslog
Validate the new changes by making a new ssh connection to your node, all these log messages will be redirected to /var/log/login_auth instead of /var/log/messages

I hope the article was useful.