我需要C语言中的日志功能或宏,它应该在Linux中工作,可以接受格式字符串和参数列表,并且可以将调用者的函数名称附加到输出字符串.
这是一个例子.假设日志记录功能(宏)称为smart_log.看起来像:
smart_log(const char *fmt, ...)
Run Code Online (Sandbox Code Playgroud)
第一个参数fmt是一个格式字符串,就像printf中的格式字符串一样.fmt之后是feed fmt的其他参数列表.
假设一个名为example_function的函数以这种方式调用smart_log:
void example_function() {
smart_log("try to output number %d\n", 1);
}
Run Code Online (Sandbox Code Playgroud)
然后日志字符串看起来像:
[example_function]: try to output number 1
Run Code Online (Sandbox Code Playgroud)
所以关键是smart_log将调用者的函数附加到格式字符串.
我不知道如何在C中实现这一点.我认为可以使用宏来实现这一目标.
函数没有可移植的方式来在C中知道它的调用者.但是你是对的,一个宏工作:
#define smart_log(...) ( printf("[%s]: ", __func__) , printf(__VA_ARGS__) )
Run Code Online (Sandbox Code Playgroud)
__func__
定义(C99/C11 6.4.2.2 p.1)
好像,紧跟在每个函数定义的开头括号之后,声明
static const char
__func__
[] = "function-name";出现了,其中function-name是词法封闭函数的名称.
感谢Hagen von Eitzen提高我原来的尝试!
归档时间: |
|
查看次数: |
953 次 |
最近记录: |