Reporting information using syslog

送分小仙女□ 提交于 2019-12-12 05:57:14

问题


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?


回答1:


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().



来源:https://stackoverflow.com/questions/18658429/reporting-information-using-syslog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!