Translate

Sunday, October 9, 2011

How to use syslog


How to use syslog for our own programs.
Linux, and other systems, supports a log management system called "syslog".
It is standard and there are utilities that can interact with it.
Here what to do to use syslog to add log capabilities to your programs.
  1. In the file where syslog is used, include :
    #include <stdarg.h>
    #include <syslog.h>
  2. Create a function that redirect the messages to syslog.
    For example this function imitate printf, just use this function everytime a message need to be printed in the syslog :
    int
    my_syslog_printf(const char *fmt, ...)
    {
       va_list ap;

       va_start( ap, fmt );
       vsyslog( LOG_INFO, fmt, ap );
       va_end( ap );
    }
  3. Before to write logs in the syslog system, the syslog file need to be opened.
    Do it before to start to use syslog :
    openlog("program_name", LOG_PID, LOG_USER);
    syslog(LOG_INFO, "Start log  --\n");
  4. Every time a log message need to be printed out, just use the function declared above, for example :
    my_syslog_printf("This is my log\n");
  5. Before to exit from the program, close the syslog using the function closelog().
    However usually exiting from the program automatically the log stream is closed by the system.

    close_log("program_name");
Note :

In openlog and closelog the "program_name" is an identifier for the particular log generator.
I usually use the program name as identifier but is not mandatory, anything that identify univocally the log stream is ok.

No comments:

Post a Comment