How to redirect output of systemd service to a file
If you have a newer distro with a newer systemd
(systemd
version 236 or newer), you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
.
Long story:
In newer versions of systemd
there is a relatively new option (the github request is from 2016 ish and the enhancement is merged/closed 2017 ish) where you can set the values of StandardOutput
or StandardError
to file:YOUR_ABSPATH_FILENAME
. The file:path
option is documented in the most recent systemd.exec
man page.
This new feature is relatively new and so is not available for older distros like centos-7 (or any centos before that).
I think there's a more elegant way to solve the problem: send the stdout/stderr to syslog with an identifier and instruct your syslog manager to split its output by program name.
Use the following properties in your systemd service unit file:
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=<your program identifier> # without any quote
Then, assuming your distribution is using rsyslog to manage syslogs, create a file in /etc/rsyslog.d/<new_file>.conf
with the following content:
if $programname == '<your program identifier>' then /path/to/log/file.log
& stop
Now make the log file writable by syslog:
# ls -alth /var/log/syslog
-rw-r----- 1 syslog adm 439K Mar 5 19:35 /var/log/syslog
# chown syslog:adm /path/to/log/file.log
Restart rsyslog (sudo systemctl restart rsyslog
) and enjoy! Your program stdout/stderr will still be available through journalctl (sudo journalctl -u <your program identifier>
) but they will also be available in your file of choice.
Source via archive.org