January 31, 2018

Note to self:Print statements not showing up on systemd logs? Do this

Let’s assume we have a service set up as follows:

[Unit]
Description=systemd_microservice

[Service]
User=USER
Group=GROUP
WorkingDirectory=systemd_working_directory
ExecStart=/usr/bin/python python_scripts.py 
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

And inside python_script.py you have a bunch of print statements.

You set up your service and your surprise when you do

sudo journalctl -f -u python_service.service

The logs dont show up!

The reason is python stdout is being buffered when redirected to journal, and thus it only shows up in blocks

How to avoid this? Easy! Just set up your parameter ExecStart in the service file like this:

[Unit]
Description=systemd_microservice, now with logs!

[Service]
User=USER
Group=GROUP
WorkingDirectory=systemd_working_directory
ExecStart=/usr/bin/python -u python_scripts.py 
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

Did you notice? the parameter -u makes forces the stdout and stderr to be unbuffered! Alternatively you can set the environment variable PYTHONUNBUFFERED to anything and will have the same effect. You can see the rest of the options for the python command line interface here

Powered by Hugo & Kiss.