• Uncategorized

About c : How-to-redirect-printf-log-to-a-specific-file-for-a-daemon-process-in-Linux

Question Detail

I have demon process ex. sample. I have service file which will trigger main process launch file. When system boots up based on this file it will create /var/log/sample.out and /var/log/sample.err file for logging.

I need to redirect printf log into this sample.out file.
Is there way I can do this?

I added below statement to do the same but its not showing any logs in /var/log/sample.out or /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

Question Answer

You cannot add arbitrary shell commands to a systemd service file. Read the documentation of systemd, in particular the part about executing binaries for how to modify the behavior of a program. To redirect standard output and error messages use:

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.