Question

I am trying to write a function which will take a priority level and a variable amount of strings as arguments to log information in an application.

The function looks something like this so far:

int _logf(int priority, char *fmt, ...)
{
    if (log.priority >= priority) {
        syslog(priority,  "LOG:%s", fmt);
    }
    /* stderr and syslog */
}

log.priority is an int set at run time which could be LOG_INFO / LOG_DEBUG / LOG_ERR

and in use:

_logf(LOG_INFO, "Starting app version %s", "1.0");

Is this an acceptable way to send log messages to syslog?

Was it helpful?

Solution

This won't work as you do not involve the variable number of parameters possibly passed into your function.

On how to do this you might take a look a the following example using vsyslog():

#include <syslog.h>
#include <stdarg.h> 

...

int _logf(int priority, const char * fmt, ...)
{
  if (log.priority >= priority) 
  {
    va_list ap;

    va_start(ap, fmt);

    vsyslog(priority, fmt, ap);

    va_end(ap);
  }
}

Then call it for example like so:

_logf(LOG_INFO, "LOG %s:%d (%s) - %s", __FILE__, __LINE__, __func__, "Just some info.");

Update:

To additionally log to stderr you might like to look ath function vfprintf().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top