C/C++ 语言调试技巧,分等级调试打印,分级别调试打印,日志记录(调试打印技巧)

参考原文,在原文基础上添加时间

C语言中的调试日志实现

在log.h 具体实现如下:

#ifndef __LOG_H__
#define __LOG_H__
 
typedef enum 
{ 
	LOG_ERROR = 1, 
	LOG_WARN = 2, 
	LOG_INFO = 3, 
	LOG_DEBUG = 4 
} LOG_LEVEL;
 
#define LOG_LEVEL_DBG LOG_DEBUG 
  
#ifdef LOG_LEVEL_DBG
#define _Log_Gen(file, func, line, level, levelStr, fmt, ...)  \
do {  \
    if (level <= LOG_LEVEL_DBG) {printf("[%s %s]: %s|%s|%s()(%d) "fmt"\n",  __DATE__, __TIME__,levelStr,file, func, line, ##__VA_ARGS__);}  \
} while(0)
#else 
#define _Log_Gen(file, func, line, level, levelStr, fmt, ...)  
#endif 
  
/* Simple APIs for log generation in different levels */ 
#define Log_d(fmt, ...) _Log_Gen(__FILE__, __FUNCTION__, __LINE__, LOG_DEBUG, "DBG", fmt, ##__VA_ARGS__) 
#define Log_i(fmt, ...) _Log_Gen(__FILE__, __FUNCTION__, __LINE__, LOG_INFO, "INF",fmt, ##__VA_ARGS__) 
#define Log_w(fmt, ...) _Log_Gen(__FILE__, __FUNCTION__, __LINE__, LOG_WARN, "WAR",fmt, ##__VA_ARGS__) 
#define Log_e(fmt, ...) _Log_Gen(__FILE__, __FUNCTION__, __LINE__, LOG_ERROR, "ERR", fmt, ##__VA_ARGS__)

#endif

使用方法如下

#include <stdio.h>
#include "log.h"
 
int addition_func(int *p_a, int *p_b, int *p_res)
{
    if (NULL == p_a || NULL == p_b || NULL == p_res)
    {
        Log_e("param is NULL, p_a:%p, p_b:%p, p_res:%p", p_a, p_b, p_res);
        return -1;
    }
    return 0;
}
 
int main(void) 
{
    int a = 1;
    int b = 2;
    int result;
    int ret = -1;
 
    ret = addition_func(&a, &b, &result);
    if (0 > ret)
    {
        Log_e("addition_func error");
        return -1;
    }
 
    Log_d("%d+%d=%d", a, b, ret);
    return 0;
}

使用效果

void DoFunction::BindData()
{   
    
    Log_d("DoFunction:BindData d");
    Log_i("DoFunction:BindData info");
    Log_w("DoFunction:BindData warning");
    Log_e("DoFunction:BindData error");
  
   
}
[Jul 13 2023 11:32:51]: DBG|DoFunction.cpp|BindData()(762) DoFunction:BindData d
[Jul 13 2023 11:32:51]: INF|DoFunction.cpp|BindData()(763) DoFunction:BindData info
[Jul 13 2023 11:32:51]: WAR|DoFunction.cpp|BindData()(764) DoFunction:BindData warning
[Jul 13 2023 11:32:51]: ERR|DoFunction.cpp|BindData()(765) DoFunction:BindData error

总结:
1、方法等级

 #define  LOG_LEVEL_DBG  LOG_DEBUG

以上这句话是定义调试输出的等级,如果我只希望输出错误信息,则配置如下:
2、如下定义

 #define  LOG_LEVEL_DBG  LOG_ERROR 

那代码里的Log_d(), Log_i(), Log_w() 就都不会打印输出了。

3、要关闭所有打印,则可以把注释掉 LOG_LEVEL_DBG,例如:

// #define LOG_LEVEL_DBG LOG_DEBUG
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值