Systemd python script won't log (buffer cause)?

nbonniot asked:

Although the problem exposed here seems very similar, none of the solutions provided work. Context :

  • Raspberry Pi Zero W, Raspbian Lite (2020-08-20)
  • I want to register a python3 script as a service, to run in background

I wanted to make it go with systemd, which worked with following configuration :

application.service lies in /etc/systemd/system/application.service

[Unit]
Description=application
After=multi-user.target


[Service]
User=custom_user
Type=idle
TimeoutSec=0
PIDFile=/run/application.pid
ExecStart=/usr/bin/python3 -u /path/to/application.py >> /path/to/log.log 2>&1
KillMode=control-group
Environment="PYTHONUNBUFFERED=1"

Restart=always
RestartSec=3s

[Install]
WantedBy=multi-user.target

This service correctly loads at startup, on expected segments (related to Wants and WantedBy sections). But it won’t log anything in log file I provided. You notice Environment entry to force PYTHONUNBUFFERED and same thing with the -u argument passed on Python executable call. This has no effect at all.

If I launch exactly the same exec line on a CLI, the script runs AND logs. Through the service definition, no log at all.

Sidenotes :

  • If i check journalctl output, I find my log lines
  • logrotate and log2ram are set up on the log file/directory

I ended up with adding my command line in /etc/rc.local followed by an ampersand. This is not a go according to me as I would like to register this service in the best way possible regarding the system it’s running on.

Thanks for your replies and enlightments.

My answer:


You shouldn’t try to use shell redirections in this manner. It doesn’t work because systemd is not a shell. Rather, specify StandardOutput= and StandardError= explicitly if you want them directed to somewhere other than the journal.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.