How to redirect output of systemd service to a file

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

I am trying to redirect o/p of a systemd service to a file but it doesn't seem to work. I am doing it as follows:

[Unit] Description=customprocess After=network.target  [Service] Type=forking ExecStart=/usr/local/bin/binary1 agent -config-dir /etc/sample.d/server StandardOutput=/var/log1.log StandardError=/var/log2.log Restart=always  [Install] WantedBy=multi-user.target 

Please suggest the correct approach to redirect o/p to a file

回答1:

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 programname.

Use the following properties in your systemd service unit file:

StandardOutput=syslog StandardError=syslog SyslogIdentifier= # without any quote 

Then, assuming your distribution is using rsyslog to manage syslogs, create a file in /etc/rsyslog.d/.conf with the following content:

if $programname == '' then /path/to/log/file.log if $programname == '' then ~ 

restart rsyslog (sudo systemctl restart rsyslog) and enjoy! Your program stdout/stderr will still be available through journalctl (sudo journalctl -u ) but they will also be available in your file of choice.

Source: http://wiki.rsyslog.com/index.php/Filtering_by_program_name



回答2:

You possibly get this error:

Failed to parse output specifier, ignoring: /var/log1.log 

From the systemd.exec(5) man page:

StandardOutput=

Controls where file descriptor 1 (STDOUT) of the executed processes is connected to. Takes one of inherit, null, tty, journal, syslog, kmsg, journal+console, syslog+console, kmsg+console or socket.

The systemd.exec(5) man page explains other options related to logging. See also the systemd.service(5) and systemd.unit(5) man pages.

Or maybe you can try things like this (all on one line):

ExecStart=/bin/sh -c '/usr/local/bin/binary1 agent -config-dir /etc/sample.d/server 2>&1 > /var/log.log'  


回答3:

If for a some reason can't use rsyslog, this will do: ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample.d/server >> /var/log/agent.log 2>&1"



回答4:

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).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!