Python: running services with logging to Rsyslog on Fedora

So, here is a task. We need to run some Python script as service with logging to Rsyslog on Fedora. As you may know,  Fedora starting from 15 uses systemd which is a replacement for SysVinit and Upstart. With use of it to setup Python service with logging is quite simple. Let’s assume we have this logger function:

from config import DEBUG
def logger(message):
    if DEBUG == 1:
        print "   ", message

Now we need to add systemd config for our service. Put if to /lib/systemd/system/web-py.service.

[Unit]
Description=web-py

[Service]
ExecStart=/usr/local/bin/web-py.py
Type=simple
User=web
Group=web
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=web-py

[Install]
WantedBy=multi-user.target

Enable it:

systemctl enable web-py.service

Let’s set up Rsyslog to store logs from our service in a way we want:

$template DynaFile,"/var/log/web/%$YEAR%/%$MONTH%/%$DAY%/%PROGRAMNAME%.log"
if $programname startswith 'web' then -?DynaFile
& ~

First line defines dynamic template DynaFile, the second one is quite self-explanatory. It says Rsyslog: if program name (SyslogIdentifier in our case) starts with ‘web’, then use DynaFile template. And the last (“& ~”) forces Rsyslog not to try to find other matches for this message, otherwise it could be also stored to /var/log/messages, for instance, which is not what we are trying to get. It should be added before other facilities.

Now start our service and restart Rsyslog:

service web-py start
service rsyslog restart

Now after your service starts working you should have its logs in files like ‘/var/log/web/2011/12/07/web_py.log’.

[root@playground ~]#tail /var/log/web/2011/12/07/web-py.log
 2011-12-07T13:39:18+01:00 playground web-py[28635]: 2011-12-07 13:31:54.348987 - +starting web-py on 0.0.0.0:8189...

Working.