使用printf函数格式化调试输出

使用C语言调试程序时,经常用printf函数,发布程序时,需要将printf函数注释,可以使用一下宏.

#define ENABLE_ALL_LEVEL_LOG (1)

#define ENABLE_DEBUG_LEVEL (1)

#define ENABLE_ERROR_LEVEL (1)

#define ENABLE_INFO_LEVEL (1)

#if ENABLE_ALL_LEVEL_LOG

#define p_debug(format, ...)\

    do {fprintf(stderr, "\033[;37m DEBUG [%s][%s][%d]:" format "\033[0m\n",\

            __FILE__,__func__,__LINE__, ##__VA_ARGS__ );\

    } while (0)  

#define p_error(format, ...)\

    do {fprintf(stderr, "\033[;31m ERROR [%s][%s][%d]:" format "\033[0m\n",\

            __FILE__,__func__,__LINE__, ##__VA_ARGS__ );\

    } while (0)  

#define p_info(format, ...)\

    do {fprintf(stderr, "\033[;32m INFO [%s][%s][%d]:" format "\033[0m\n",\

            __FILE__,__func__,__LINE__, ##__VA_ARGS__ );\

    } while (0)  

#else

    #if ENABLE_DEBUG_LEVEL

        #define p_debug(format, ...)\

        do {fprintf(stderr, "\033[;37m DEBUG [%s][%s][%d]:" format "\033[0m\n",\

                __FILE__,__func__,__LINE__, ##__VA_ARGS__ );\

        } while (0)  

    #else

        #define p_debug(format, ...)

    #endif

    #if ENABLE_ERROR_LEVEL

        #define p_error(format, ...)\

        do {fprintf(stderr, "\033[;31m ERROR [%s][%s][%d]:" format "\033[0m\n",\

                __FILE__,__func__,__LINE__, ##__VA_ARGS__ );\

        } while (0)  

    #else

    #define p_error(format, ...)

    #endif

    #if ENABLE_INFO_LEVEL

        #define p_info(format, ...)\

        do {fprintf(stderr, "\033[;32m INFO [%s][%s][%d]:" format "\033[0m\n",\

                __FILE__,__func__,__LINE__, ##__VA_ARGS__ );\

        } while (0)  

    #else

        #define p_info(format, ...) 

    #endif



#endif

具体颜色可以参考这里:

C语言中默认的printf打印都是一种颜色的,有时候为了突出显示其中的信息,避免重要的警告(warning)和错误(error)信息淹没在其他不重要的log中,有必要区别不同信息级别的字体颜色。

格式 printf(
"\033[字背景颜色;字体颜色m字符串\033[0m" ); 例如, printf("\033[47;31mThis is a color test.\033[0m"); 47是字背景颜色, 31是字体的颜色, This is a color test.是字符串. \033[0m是控制码. 颜色打印 附录 部分颜色代码: 字背景颜色: 40--49 字颜色: 30--39 40: 黑 30: 黑 41: 红 31: 红 42: 绿 32: 绿 43: 黄 33: 黄 44: 蓝 34: 蓝 45: 紫 35: 紫 46: 深绿      36: 深绿 47:白色 37:白色

 

posted @ 2021-01-22 17:15  jest549  阅读(290)  评论(0编辑  收藏  举报