Write to custom log file from a Bash script

前端 未结 5 607
渐次进展
渐次进展 2021-02-03 18:47

In Linux, I know how to write a simply message to the /var/log/messages file, in a simple shell script I created:

#!/bin/bash
logger \"have fun!\"
<         


        
5条回答
  •  醉梦人生
    2021-02-03 19:18

    I did it by using a filter. Most linux systems use rsyslog these days. The config files are located at /etc/rsyslog.conf and /etc/rsyslog.d.

    Whenever I run the command logger -t SRI some message, I want "some message" to only show up in /var/log/sri.log.

    To do this I added the file /etc/rsyslog.d/00-sri.conf with the following content.

    # Filter all messages whose tag starts with SRI
    # Note that 'isequal, "SRI:"' or 'isequal "SRI"' will not work.
    #
    :syslogtag, startswith, "SRI" /var/log/sri.log
    
    # The stop command prevents this message from getting processed any further.
    # Thus the message will not show up in /var/log/messages.
    #
    & stop
    

    Then restart the rsyslogd service:

    systemctl restart rsyslog.service
    

    Here is a shell session showing the results:

    [root@rpm-server html]# logger -t SRI Hello World!
    [root@rpm-server html]# cat /var/log/sri.log
    Jun  5 10:33:01 rpm-server SRI[11785]: Hello World!
    [root@rpm-server html]#
    [root@rpm-server html]# # see that nothing shows up in /var/log/messages
    [root@rpm-server html]# tail -10 /var/log/messages | grep SRI
    [root@rpm-server html]#
    

提交回复
热议问题