Hello,阳光柠檬! 养成记录笔记的好习惯

优化打印调试信息(可变参数)

2013-10-29
liukang
C++

此博客均属原创或译文,欢迎转载但请注明出处 GithubPage:https://liukang325.github.io

#include <stdio.h>      
#include <stdarg.h>      
      
#define MAX_MSG     1000      
//#define __D(fmt, args...)  printf("debug: " fmt, ## args)      
#define __D(fmt,...)  logOut(__FILE__,__FUNCTION__,__LINE__,fmt"",##__VA_ARGS__)      
      
int logOut(const char *file, const char *func, const int line, const char *fmt, ...)        
{        
    char msg[MAX_MSG]={0};        
    if(NULL != fmt)            
    {        
        va_list ap;            
        va_start(ap, fmt);        
        vsnprintf(msg, sizeof(msg), fmt, ap);        
        va_end(ap);            
    }         
    time_t tnow;        
    struct tm *tmnow;        
    time(&tnow);        
    tmnow = localtime(&tnow);        
      
    //usec      
    struct timeval tv;      
    if(gettimeofday(&tv,NULL)<0)      
        return 0;      
    
    printf("%4d-%02d-%02d %02d:%02d:%02d.%06d %s:%s():%d  %s",       
            (1900 + tmnow->tm_year),(1 + tmnow->tm_mon),      
            tmnow->tm_mday,      
            tmnow->tm_hour,tmnow->tm_min,tmnow->tm_sec,tv.tv_usec,    
            file, func, line, msg);    
}      
int main()      
{       
    int n = 8;      
    __D("hello world n = %d\n",n);      
}   

最简单的宏定义

#include <stdio.h>  
  
#define DEBUG     
    
#ifdef DEBUG        
#define __D(msg, args...) fprintf(stderr, "[lk] - %s-%s():%d: " msg, __FILE__, __FUNCTION__, __LINE__, ##args)  
#else  
#define __D(msg, args...) ((void)0)  
#endif  
  
int main()  
{  
    __D("123\n");  
    return 0;  
}  

QT中的一种用法

#define QDBG qDebug()<<__FILE__<<__FUNCTION__<<"():"<<__LINE__  

只显示文件名,不显示文件路径的logOut

static void logOut(const char *file, const char *func, const int line, const char *fmt, ...)  
{  
    char msg[MAX_MSG]={0};  
    if(NULL != fmt)  
    {  
        va_list ap;  
        va_start(ap, fmt);  
        vsnprintf(msg, sizeof(msg), fmt, ap);  
        va_end(ap);  
    }  
    std::string fileStr(file);  
    int backslashIndex = fileStr.find_last_of('/');  
    printf("[DBG] %s ", fileStr.substr(backslashIndex+1,-1).c_str());  
    printf("%s():%d  %s", func, line, msg);  
}  

Similar Posts

Comments