编程者所写的第一个程序,就是使用printf打印“Hello world”。其实printf的功效远不只这些,在程序调试方面,printf也有非常大的用处。下面我就总结一下使用日志打印辅助debug的心得。
一般来说,初学日志打印的注意事项
在编写程序后,我们可以随手在需要的地方加入打印信息,同时需要考虑如下事项:
日志输出是有代价的,特别是在嵌入式系统,或者对执行时序要求较高的应用场景。因此:
a) 只有在需要的地方加入,不能滥用。
b) 一定要有一个全局的开关,在不需要或者产品发布的时候,关闭输出,或者降低日志输出的频率。
日志输出需要有优先级控制,例如:发生错误时的日志优先级最高,一般都要输出;一些重要的提示,优先级中等,可能会在debug版的软件中打开;一些不重要的提示,可能只会在需要的时候(例如跟踪bug)打开。
不要直接使用printf(或者printk)。日志输出的目标是多样的,例如通过printf输出到屏幕、通过串口输出到串口调试助手、通过文件操作写入到文件等等。
要通过重定义的方式,将所有的日志输出指令定义到合适的输出路径,当需要修 改输出路径的时候,只要修改重定义的部分即可。否则需要在整个代码中修改, 就麻烦了。
最好为每个软件模块提供单独的日志输出开关,以增加调试的灵活性。
很多时候,日志输出语句,可以部分代替代码注释的功能。
日志打印的实现
结合上面的注意事项,我们可以按照如下步骤实现一个小型的日志输出系统。
新建debug.h(如果只是在PC上使用printf,则只需要一个头文件即可。如果有需要文件或者串口操作,可以在这个基础上增加debug.c,这里暂时不再描述)
定义一个宏开关,用于控制日志输出的开关。
/* * debug control, you can switch on (delete 'x' suffix) * to enable log output and assert mechanism */ #define CONFIG_ENABLE_DEBUG
3.定义ERR、INFO、DEBUG三个日志级别。
/* 定义ERR、INFO、DEBUG三个日志级别。 /* * debug level, * if is DEBUG_LEVEL_DISABLE, no log is allowed output, * if is DEBUG_LEVEL_ERR, only ERR is allowed output, * if is DEBUG_LEVEL_INFO, ERR and INFO are allowed output, * if is DEBUG_LEVEL_DEBUG, all log are allowed output,
4.如果使用系统的printf,需要包含stdio.h,并将printf重定义为PRINT。(无论是Windows还是Linux,皆是如此,如果是嵌入式平台,可以自定义PRINT接口)
/* it can be change to others, such as file operations */ #include <stdio.h> #define PRINT printf
5.定义一个宏,用于定义日志输出级别。
/* * the macro to set debug level, you should call it * once in the files you need use debug system */ #define DEBUG_SET_LEVEL(x) static int debug = x
需要在每一个需要日志输出的C文件中调用,如下:
/* * define the debug level of this file, * please see 'debug.h' for detail info */ DEBUG_SET_LEVEL(DEBUG_LEVEL_ERR);
6.定义ASSERT、ERR、INFO、DEBUG等宏 。
#define ASSERT() \ do { \ PRINT("ASSERT: %s %s %d", \ __FILE__, __FUNCTION__, __LINE__); \ while (1); \ } while (0) #define ERR(...) \ do { \ if (debug >= DEBUG_LEVEL_ERR) { \ PRINT(__VA_ARGS__); \ } \ } while (0) …
7.在需要日志输出的C文件中,包含debug.h,并定义所需的日志级别。就可以在需要的时候输出日志信息了。
debug_test.c ----------------------------------------------------- #include "debug.h" /* * define the debug level of this file, * please see 'debug.h' for detail info */ DEBUG_SET_LEVEL(DEBUG_LEVEL_ERR); int main(void) { ERR("This is a error message\n"); INFO("This is a info message\n"); DEBUG("This is a debug message\n"); ASSERT(); return 0; }
Step8. 可以根据需要,修改容许输出的日志级别。
发表评论 取消回复