How to Pipe Output to a File When Running as a Systemd Service

How to redirect output of systemd service to a file

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

Piping systemd output into a file

Put your command line in a file:

#!/bin/bash
/usr/local/byond/bin/DreamDaemon /home/ss13/ss13/baystation12.dmb 25565 -trusted >> /home/ss13/ss13-log

Then have ExecStart= reference that file.

systemd service redirect stdout to custom filename

systemd cannot generate the file name dynamically. But you can use bash redirection and date to create such a logfile.

[Service]
ExecStart=/bin/bash -c "/bin/mybin >/my/path/filename-$(date %%y-%%d-%%m).log"

send stdout/stderr to console for a systemd service

I wanted to do something similar, and setting StandardOutput=journal+console worked for me. FWIW this is the relevant systemd documentation https://www.freedesktop.org/software/systemd/man/systemd.exec.html.

In your case you want want to look at the TTYPath option, specifically the default value of systemd vs the default on your system. HTH.

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

Normally you just run a service directly (make sure it's executable has a shebang line):

 ExecStart=/home/pi/sources/mydaemon.py

And use the default redirection of StandardOutput= to the systemd journal, so you can read the logs with journalctl -u mydaemon.service.

Systemd nicely controls the file growth and file rotation of the log for you.

It is unrelated that your service runs as root.

If you don't see any log output with the above, also check the entire log for nearby logs that might be attributed to your service:

 journalctl

This is necessary because there's a known issue when some last lines of logging just before a script exists might not be attributed to the script. This would be especially noticeable for a script that just runs a fraction of a second before exiting.



Related Topics



Leave a reply



Submit