
概述本章节通过示例阐述printf分级控制打印实现细节注意事项必要的地方加日志输出是有代价的特别是针对嵌入式这类实时性要求较高的系统需要有宏开关调试版本打开发布版本关闭需要有级别控制便于调试输出使用宏替换printf、printk以便修改宏即可修改所有地方针对各个模块可以单独控制打印内容意义清晰便于排查问题具体实现公共头文件定义宏开关/* * debug control, you can switch on (delete x suffix) * to enable log output and assert mechanism */ #define CONFIG_ENABLE_DEBUGdebug.h定义打印级别/* * 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, */ enum debug_level { DEBUG_LEVEL_DISABLE 0, DEBUG_LEVEL_ERR, DEBUG_LEVEL_INFO, DEBUG_LEVEL_DEBUG };使用宏替换/* it can be change to others, such as file operations */ #include stdio.h #define PRINT printf定义宏用于控制输出级别/* * 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定义打印宏#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) …示例----------------------------------------------------- #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; }