brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: StandardOutput=append: writes a systemd service's output to a plain log file

Systemd
~/tips/tip-systemd-standardoutput-append-file

sudo systemctl edit myapp.service

Sends a service's output to a normal text log file instead of the journal.

The journal is where I’d normally want service output. But now and then something else needs a plain text file: a log shipper that only reads files, or a colleague who simply refuses to learn journalctl. systemd can write it there for you, without a shell redirect in ExecStart=.

StandardOutput= decides where stdout of the service goes, and append: opens a file in append mode. StandardError= defaults to inherit, which duplicates stdout, so with one line both streams end up in the same file:

sudo systemctl edit myapp.service

[Service]
StandardOutput=append:/var/log/myapp.log
StandardError=inherit

After sudo systemctl restart myapp the output goes to /var/log/myapp.log. Want errors apart? Give StandardError= its own append:/var/log/myapp.err. There is also file:, which writes from the start of the file without truncating it (so you get a mess of old and new text), and truncate:, which empties it on every start. I’d stick with append:.

Some caveats. That output no longer goes to the journal, so journalctl -u myapp only shows systemd’s own start and stop lines. The file is created by the service manager if it doesn’t exist, so it belongs to root; the service still writes to it because systemd hands it the open file. And nothing rotates this file. A logrotate rule with copytruncate fits, because the service keeps its file open and never reopens it; logrotate’s manual does warn that a few lines can be lost between the copy and the truncate.

/var/log/myapp.log {
    weekly
    rotate 4
    compress
    copytruncate
}

Further reading: systemd.exec(5) manual page, logrotate(8) manual page

More Systemd tips [Service] sudo mkdir -p /etc/systemd/system/service.d [Service] printf 'hunter2' | sudo systemd-creds encrypt --name=dbpass – dbpass.cred systemd-analyze timespan 1h30min All Systemd tips (88) All topics

Link