How do I properly redirect stdout/stderr from a systemd service on Raspbian?

Eric picture Eric · Apr 25, 2017 · Viewed 9.8k times · Source

I set up a service on Raspbian (Jessie) using systemd to make it start after boot. The daemon config looks like this:

[Unit]
After=multi-user.target

[Service]
Type=idle
User=root
ExecStart=/bin/sh -c "exec /home/pi/sources/mydaemon.py >> /home/pi/mydaemon.log 2>&1"

[Install]
WantedBy=multi-user.target

That redirection >> isn't working. I have tried most of the options available to the StandardOutput and StandardError but they never end up printing my script's output to /var/log/daemon.log and journalctl -u mydaemon.service only shows messages about the service being started and stopped.

I'm not doing anything funny with file descriptors from within the script currently. I just want my print() or logging.info() statements to show up somewhere I can read them. Any ideas?

(Just to be clear, the daemon does have to run as root. Could that have something to do with my printing problem?)

Answer

Pengman picture Pengman · Aug 28, 2017

I needed to run python with the -u parameter to ensure messages were not buffered.

With these lines, the print lines gets added to the journal immediately:

StandardOutput=journal+console
ExecStart=/home/pengman/scripts/mqtt_monitor/venv/bin/python -u home/pengman/scripts/mqtt_monitor/src/mqtt_monitor.py

(I am running inside a virtualenv, but that shouldn't matter)