使用syslog报告信息

时间:2013-09-06 12:58:27

标签: c logging syslog

我正在尝试编写一个函数,它将优先级和可变数量的字符串作为参数来记录应用程序中的信息。

到目前为止,该函数看起来像这样:

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

log.priority在运行时设置为int,可以是LOG_INFO / LOG_DEBUG / LOG_ERR

并在使用中:

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

这是将日志消息发送到syslog的可接受方式吗?

1 个答案:

答案 0 :(得分:1)

这不起作用,因为您不涉及可能传递给函数的可变数量的参数。

关于如何执行此操作,您可以使用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);
  }
}

然后将其称为例如:

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

<强>更新

要另外登录stderr,您可能希望查看功能vfprintf()