Daemon logging in Linux

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?


Solution 1:

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;
}

Solution 2:

This is probably going to be a was horse race, but yes the syslog facility which exists in most if not all Un*x derivatives is the preferred way to go. There is nothing wrong with logging to a file, but it does leave on your shoulders an number of tasks:

  • is there a file system at your logging location to save the file
  • what about buffering (for performance) vs flushing (to get logs written before a system crash)
  • if your daemon runs for a long time, what do you do about the ever growing log file.

Syslog takes care of all this, and more, for you. The API is similar the printf clan so you should have no problems adapting your code.