Daemon logging in Linux

codemonkey picture codemonkey · Oct 1, 2008 · Viewed 60.5k times · Source

So I have a daemon running on a Linux system, and I want to have a record of its activities: a log. The question is, what is the "best" way to accomplish this?

My first idea is to simply open a file and write to it.

FILE* log = fopen("logfile.log", "w");
/* daemon works...needs to write to log */
fprintf(log, "foo%s\n", (char*)bar);
/* ...all done, close the file */
fclose(log);

Is there anything inherently wrong with logging this way? Is there a better way, such as some framework built into Linux?

Answer

Vinko Vrsalovic picture Vinko Vrsalovic · Oct 1, 2008

Unix has had for a long while a special logging framework called syslog. Type in your shell

man 3 syslog

and you'll get the help for the C interface to it.

Some examples

#include <stdio.h>
#include <unistd.h>
#include <syslog.h>

int main(void) {

 openlog("slog", LOG_PID|LOG_CONS, LOG_USER);
 syslog(LOG_INFO, "A different kind of Hello world ... ");
 closelog();

 return 0;
}