我需要一个 C 语言的日志记录函数或宏,它应该在 Linux 中工作,可以接受格式字符串和参数列表,并且可以将调用者的函数名称附加到输出字符串。
这是一个例子。假设日志记录函数(宏)称为 smart_log。看起来像:
smart_log(const char *fmt, ...)
第一个参数 fmt 是格式字符串,就像 printf 中的格式字符串一样。 fmt 之后是 feed fmt 的附加参数列表。
假设一个名为 example_function 的函数以这种方式调用 smart_log:
void example_function() {
smart_log("try to output number %d\n", 1);
}
然后日志字符串看起来像:
[example_function]: try to output number 1
所以关键点是smart_log将调用者的函数附加到格式字符串。
我不确定如何在 C 中实现这一点。我认为可以使用宏来实现这一点。
最佳答案
在 C 语言中,函数没有可移植的方式来知道它的调用者。但是你是对的,宏可以工作:
#define smart_log(...) ( printf("[%s]: ", __func__) , printf(__VA_ARGS__) )
__func__
已定义(C99/C11 6.4.2.2 p.1)
as if, immediately following the opening brace of each function definition, the declaration
static const char <code>__func__</code>[] = "<i>function-name</i>";
appeared, where function-name is the name of the lexically-enclosing function.
感谢Hagen von Eitzen为了改进我最初的尝试!
关于c - 如何编写可以将调用者的名称附加到 C 中的日志输出的日志记录函数或宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493774/