我试图重定向输出的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

请纠正我的做法。


当前回答

在我的例子中,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

其他回答

假设日志已经放在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

如果由于某种原因不能使用rsyslog,这将做: ExecStart=/bin/bash -ce "exec /usr/local/bin/binary1 agent -config-dir /etc/sample. exe "D /server >> /var/log/agent.log 2>&1"

让你的服务文件调用shell脚本,而不是直接运行应用程序。这样你就有了额外的控制权。例如,您可以创建类似于/var/log/中的输出文件

编写一个shell脚本,如/opt/myapp/myapp.sh

#!/bin/sh
/usr/sbin/logrotate --force /opt/myapp/myapp.conf --state /opt/myapp/state.tmp
logger "[myapp] Run" # send a marker to syslog
myapp > /opt/myapp/myapp.log 2>&1 &

和你的服务文件myapp。服务包含:

...
[Service]
Type=forking
ExecStart=/bin/sh -c /opt/myapp/myapp.sh
...

日志配置文件/opt/myapp/myapp.conf的示例

/opt/myapp/myapp.log {
    daily
    rotate 20
    missingok
    compress
}

然后你会得到myapp.log,并压缩myapp.log.1.gz…每次服务被启动,和以前压缩。

我建议在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