c - 如何编写可以将调用者的名称附加到 C 中的日志输出的日志记录函数或宏

标签 c logging macros

我需要一个 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/

相关文章:

更改 C 签名以接受字符数组而不是整数数组

c - 如何在不进行系统调用的情况下获取线程ID?获取系统时间与使用系统调用获取线程 ID 相比,花费的时间更少、更多还是相同?

loops - SPSS 语法宏重复性

macros - 如何在 Rust 程序宏中创建多个项目?

multithreading - 将对象参数传递给宏

c++ - 如何用c++求公因数?

c - const 对字符串文字 C 数组的作用

c - 减少操作次数

重定向到文件时 Python 日志出现较晚

java - 使用 FOP 时禁用 Log4j INFO 级别日志记录