我需要更改宏(日志宏)的实现
打印到系统日志。
宏用法:
LOGGING_MACRO(5,("Value of x,y=%d,%d\n",x,y));
定义1:
#define LOGGING_MACRO(loglevel,str) printf str;
定义2:
#define LOGGING_MACRO(loglevel,str) syslog(loglevel,str);
注意:我无法更改宏格式:(
Def2抛出错误,因为syslog不接受带有前后大括号的'str'(第二个arg)。[但在使用printf的Def1中运行良好]
请建议在将“str”传递给syslog之前,如何从宏的“str”中删除第一个和最后一个大括号。
最佳答案
以下示例适用于单线程应用程序:
char* custom_log(const char *fmt, ...) {
static char outputString[200]; //Adjust your size for maximal log value
va_list args;
va_start(args, fmt);
vsprintf(outputString, fmt, args);
va_end(args);
return outputString;
}
然后将宏修改为:
#define LOGGING_MACRO(loglevel,str) syslog(loglevel, custom_log str)
记住,这只在单线程模式下工作,并确保在调用自定义日志函数的地方,
custom_log
函数可见。对于多线程,您可以这样更新它:
#define LOGGING_MACRO(loglevel,str) do {\
mutex_lock(); /*Lock your mutex for debug print*/ \
syslog(loglevel, custom_log str); /*Debug*/ \
mutex_unlock(); /*Unlock mutex*/ \
} while (0)
请记住,为了满足系统中的需求,您必须编写
mutex_lock
和mutex_unlock
函数,以便仅在多线程之间锁定调试函数。