【问题标题】:How to redirect printf log to a specific file for a daemon process in Linux?如何将 printf 日志重定向到 Linux 中守护进程的特定文件?
【发布时间】:2022-01-05 20:59:26
【问题描述】:

我有恶魔进程前。样本。我有将触发主进程启动文件的服务文件。当系统基于此文件启动时,它将创建/var/log/sample.out/var/log/sample.err 文件用于日志记录。

我需要将 printf 日志重定向到这个 sample.out 文件中。 有没有办法做到这一点?

我添加了下面的语句来做同样的事情,但它没有在 /var/log/sample.out/var/log/sample.err 中显示任何日志。

${binary} > ${logs}.out 2> ${logs}.err

sample.c

#include<stdio.h>
int main()
{
    printf("Demon starteed \n");
}

sample.service

[Unit]
Description="sample service"

[Service]
ExecStart=/usr/bin/sample.service.start

[Install]
WantedBy=multi-user.target

sample.service.start

service=sample
binary=/usr/bin/${service}
logs=/var/log/${service}
${binary} > ${logs}.out 2> ${logs}.err

【问题讨论】:

  • I need to 为什么你需要?您不想使用系统日志记录功能吗?而且,stackoverflow.com/a/48052152/9072753 应该会回答您的问题。
  • @KamilCuk 我需要这样做是为了调试而不是生产

标签: c linux daemon systemctl


【解决方案1】:

您不能将任意 shell 命令添加到 systemd 服务文件。阅读 systemd 的文档,尤其是 the part about executing binaries,了解如何修改程序的行为。要重定向标准输出和错误消息,请使用:

StandardOutput=/var/log/sample.out
StandardError=/var/log/sample.err

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2018-01-11
    相关资源
    最近更新 更多