Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to send the message produced by perror() to /var/log/syslog?

I'm using perror() to print error messages, like:

pid = fork();
if (pid < 0) {
    perror("couldn't fork");
    exit(EXIT_FAILURE);
}

Is it possible to use errno/perror() facilities but direct the produced messages to the system log (/var/log/syslog)?

I ask this in the context of a program which can be run in both daemon and non-daemon modes. In daemon mode, perror() messages won't appear on syslog.

like image 297
João M. S. Silva Avatar asked Dec 10 '22 19:12

João M. S. Silva


2 Answers

Use strerror to get the error message based on an error code, without printing it. Then pass it to syslog like any other log message:

syslog(LOG_ERR, "Couldn't fork: %s", strerror(errno));
like image 125
user253751 Avatar answered Dec 28 '22 18:12

user253751


The easiest way is to redirect stderr (and possibly stdout) when you call your program. For example: ./myprog 2>&1 | logger.

like image 37
paulsm4 Avatar answered Dec 28 '22 18:12

paulsm4