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?
There are two ways to implement logging in a Linux daemon process: syslog - which is not supported by Java - or just creating a file and writing to it. For the latter, professional programmers usually use a logging framework like log4j, logback or a wrapper like slf4j. I could find my logs in /var/log/syslog .
The system logging daemon syslogd, also known as sysklogd, awaits logging messages from numerous sources and routes the messages to the appropriate file or network destination.
The syslog daemon is a server process that provides a message logging facility for application and system processes. The syslog daemon is started by the Internet Daemon and receives messages on well-known port 514. The syslog daemon must be started before any application program or system process that uses it starts.
This is such a crucial folder on your Linux systems. Open up a terminal window and issue the command cd /var/log. Now issue the command ls and you will see the logs housed within this directory (Figure 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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With