我试图重定向输出的systemd服务到一个文件,但它似乎不工作:

[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

请纠正我的做法。


当前回答

简短的回答:

StandardOutput=file:/var/log1.log
StandardError=file:/var/log2.log

如果你不希望每次服务运行时文件都被清除,使用append代替:

StandardOutput=append:/var/log1.log
StandardError=append:/var/log2.log

其他回答

我建议在systemd服务文件中添加stdout和stderr文件。

参考:https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=

正如你所配置的那样,它不应该是这样的:

StandardOutput=/home/user/log1.log
StandardError=/home/user/log2.log

它应该是:

StandardOutput=file:/home/user/log1.log
StandardError=file:/home/user/log2.log

当您不想一次又一次地重新启动服务时,这种方法是有效的。

这将创建一个新文件,而不会追加到现有文件。

使用:

StandardOutput=append:/home/user/log1.log
StandardError=append:/home/user/log2.log

注意:确保已经创建了目录。我猜它不支持创建目录。

简短的回答:

StandardOutput=file:/var/log1.log
StandardError=file:/var/log2.log

如果你不希望每次服务运行时文件都被清除,使用append代替:

StandardOutput=append:/var/log1.log
StandardError=append:/var/log2.log

假设日志已经放在stdout/stderr中,并且systemd单元的日志在/var/log/syslog中

journalctl -u unitxxx.service

Jun 30 13:51:46 host unitxxx[1437]: time="2018-06-30T11:51:46Z" level=info msg="127.0.0.1
Jun 30 15:02:15 host unitxxx[1437]: time="2018-06-30T13:02:15Z" level=info msg="127.0.0.1
Jun 30 15:33:02 host unitxxx[1437]: time="2018-06-30T13:33:02Z" level=info msg="127.0.0.1
Jun 30 15:56:31 host unitxxx[1437]: time="2018-06-30T13:56:31Z" level=info msg="127.0.0.1

配置rsyslog(系统日志服务)

# Create directory for log file
mkdir /var/log/unitxxx

# Then add config file /etc/rsyslog.d/unitxxx.conf

if $programname == 'unitxxx' then /var/log/unitxxx/unitxxx.log
& stop

重新启动 rsyslog

systemctl restart rsyslog.service

如果您有一个更新的systemd发行版(systemd版本236或更新版本),您可以将StandardOutput或StandardError的值设置为file:YOUR_ABSPATH_FILENAME。


长故事:

在systemd的新版本中,有一个相对较新的选项(github请求来自2016年左右,增强是合并/关闭2017年左右),您可以将StandardOutput或StandardError的值设置为file:YOUR_ABSPATH_FILENAME。file:path选项记录在最近的systemd中。Exec手册页。

这个新功能相对较新,因此不适用于以前的发行版,如centos-7(或在此之前的任何centos)。

在我的例子中,2>&1(stdout和stderr文件描述符符号)必须正确放置,然后日志重定向工作如我所料

[Unit]
Description=events-server

[Service]
User=manjunath
Type=simple
ExecStart=/bin/bash -c '/opt/events-server/bin/start.sh my-conf   2>&1 >> /var/log/events-server/events.log'

[Install]
WantedBy=multi-user.target