当开发人员添加在C和C ++中调用函数log_message的代码时,我需要跟踪某个日志级别的每个日志消息。
这是为了在项目中进行日志消息管理,以避免太多的开发人员在源代码中添加太多不遵循相同约定的消息。
例如:
file1.c:
log_message("Module:Failed to create the file %s\n", file_name);
file2.c:
log_message("Failed to create the XXXX file %s\n", file_name);
MESSAGE_1000在另一个文件message.h中定义,该文件由我们的消息数据库生成。 message.h:
const char* MESSAGE_1000 = “Module: Failed to create the file %s.\n”
文件预编译后:
file1.c变为:
#include "message.h"
...
log_message(MESSAGE_1000,file_name)
file2.c变为:
#include "message.h"
...
log_message(MESSAGE_1000,file_name)
当他们需要向日志消息数据库中添加一些新消息时。
他们可以使用钩子可以识别的固定功能名称。
例如:
file1.c:
log_message_new("My new message:%s", message)
在编译期间:
message.h已更新为:
#defined MESSAGE_1001 "My new message:%s", message
在我们的消息数据库中,添加了一个新条目。
MESSAGE_1001="My new message:%s"
为什么有消息数据库?它们是针对非开发人员的。他们可以查看客户可能看到的所有日志消息。
在这里,我需要一个钩子来捕获和修改源代码。
您有什么想法吗?
答案 0 :(得分:2)
gcc中有一个选项有时会用于这种情况。您可以在链接期间使用-Wl,--wrap
模拟该函数,请参见GNU ld linker options。
您将需要一个简单的编译单元:
extern "C" void __real_log_message(...);
extern "C" void __wrap_log_message(...) {
.... // do something with the arguments
__real_log_message(...); // call real function
}
将这些符号添加到您的链接过程中,并提供-Wl,--wrap=log_message
链接选项,您一切顺利。