Search code examples
python-3.xloggingsyslogrsyslog

Log to rsyslog facility from a python script


I have this in my /etc/rsyslog.conf:

local0.*     /var/log/local.log

And I have a simple python script which reads from standard input and is supposed to send to local0

#!/usr/bin/python3

import sys, syslog

syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)

for line in sys.stdin:
    syslog.syslog(syslog.LOG_WARNING, f"Message\n\n")

But it does not work. rsyslog does not see the messages as comming to local0

Only when I change to *.* does rsyslog see it:

*.*     /var/log/local.log

I assume I don't properly configure the facility in my python script.

How can I specify I want to log to local0 ?


Solution

  • Rsyslog and local*:

    Rsyslog have the facilities local0 to local7 that are "custom" unused facilities that syslog provides for the user. If a developer create an application and wants to make it log to syslog, or if you want to redirect the output of anything to syslog (for example, Apache logs), you can choose to send it to any of the local# facilities. Then, you can use /etc/syslog.conf (or /etc/rsyslog.conf) to save the logs being sent to that local# to a file, or to send it to a remote server (source).

    Config:

    Under /etc/rsyslog.conf

    local0.*     /var/log/local.log
    

    This is correct and it assign the log file /var/log/local.log to apps that log to local0. As an other example kern.=warn -/var/log/kernel/warnings.log can be used to log kernel warnings.

    Python application/script:

    #!/usr/bin/python3
    import sys, syslog
    
    syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)
    
    for line in sys.stdin:
        syslog.syslog(syslog.LOG_WARNING, f"Message {line}\n\n")
    

    The initial code does work, and as pointed in the comments this can be used as an alternative and {line} variable have been added as suggested by @apoorva-kamath...

    The important side here is on the communication between the Python script and Rsyslog.

    Also as pointed on the command try is to reload rsyslog systemctl restart rsyslog; you can as well check the Rsyslog config with rsyslogd -N1 and check if rsyslog is working correctly with:

    sudo cat /var/log/messages | grep rsyslog
    

    Depending on the Python script running context, communications to Rsyslog may fail, further details on your config are needed otherwise you can try (from the script's context):

    logger -p local0.error "TroubleshootingTest"
    

    And finally check the data transmission with:

    sudo netstat -taupn | grep syslog
    

    Documentations:

    More details about Python syslog, troubleshooting Rsyslog and Rsyslog facility