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

I use perror () to print error messages, for example:

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

Is it possible to use objects errno/perror(), but send received messages to the system log ( /var/log/syslog)?

I ask about this in the context of a program that can be run in both daemon and non-daemon mode. In daemon mode, messages are perror()not displayed in syslog.

+4
source share
3 answers

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

syslog(LOG_ERR, "Couldn't fork: %s", strerror(errno));
+7

, syslog, , . fprintf stderr , .

+2

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

+1
source

Source: https://habr.com/ru/post/1619426/


All Articles