Question

Consider the following program:

#include <syslog.h>

int main()
{
    openlog("test-app", LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);
    setlogmask(LOG_UPTO(LOG_DEBUG));

    syslog(LOG_DEBUG, "Testing!");
}

Note the use of LOG_PERROR, which emits messages to stderr as well as whatever file syslogd is configured to fill (in my case, /var/log/messages).

The console output is:

test-app[28072]: Testing!

The syslog file contains:

Apr 17 13:20:14 cat test-app[28072]: Testing!

Can I configure syslog so that the console output contains timestamps also? If so, how?

Was it helpful?

Solution

This is not doable when using the syslog call on it's own. The reason is that the timestamp that you see on the log file is after the log message has been sent to the daemon. It's the syslog daemon that actually performs the addition of the timestamp. The logging daemon is the thing that applies the timestamp.

When you use the LOG_CONS and LOG_PERROR options the message is sent to the console or stderr without ever getting timestamped because the timestamping does not occur at the point of logging.

Essentially the use of LOG_CONS and LOG_PERROR bypass the daemon entirely; you would need to modify the implementation of the syslog call itself to add your own timestamp. Thankfully, that's pretty easy as the implementation of the syslog library call is in the glibc source, and the source isn't terribly complicated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top