-1

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

2

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.

Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
  • Modifying glibc makes deployment quite a lot more complicated, though, so this is a shame. – Lightness Races in Orbit Apr 17 '14 at 14:26
  • You don't need to modify glibc, you can implement your own syslog equivalent in a small library and use that in your code. At it's core, all the syslog call does is write a simple message to `/dev/log`, the format of which is `Message` i.e. get the decimal representation of facility | priority and put it into `<>` and send that to `/dev/log` e.g. user.warn == (1 << 3) | 4 so the message is `<12>Message` will get put into wherever the user.warn messages go. (you can test this using `echo "<12>Message" | socat stdin unix-sendto:/dev/log` to see it being logged – Anya Shenanigans Apr 17 '14 at 15:15
  • Yeah, could do. Feels a bit NIH, though; not sure I'd get it past code review for relatively little gain. – Lightness Races in Orbit Apr 17 '14 at 16:38
  • I've got a crummy piece of java code which does that because it was easier than writing a JNI stub to call `syslog`. – Anya Shenanigans Apr 17 '14 at 16:43