自己的出错处理之-debug.c

27 篇文章 0 订阅

在本c文件对应的头文件中直接定义宏定义REP 即可写到文件中!

在这包含本应用用到的所有头文件( 头文件的定义要严格按照 debug.h 的方式定义 来防止函数定义的冲突)

#ifdef __cplusplus

extern "C" {
#endif 


#define REP_LOG_FILE "/tmp/.rep_log"
#define REP_DEBUG_BUFFER_SIZE 2048

//定义外部对象 g_iDebug  作为调试开关!

int g_iDebug = 1;


void REP_DEBUG_Printf(const char *szFunction, const char *szFile, const int iLine, char *pcFmt, ...)
{
    char acDebugBuffer[REP_DEBUG_BUFFER_SIZE];
    time_t now;
    struct tm *pstTm;
    va_list ap;
    FILE *stream;
    if(0 == g_iDebug)
    {
        return;
    }

    va_start(ap, pcFmt);

//使用vsnprintf 代替vsprintf 可以避免数组越界.
    vsnprintf (acDebugBuffer,REP_DEBUG_BUFFER_SIZE ,pcFmt, ap);
    va_end(ap);
    now = time(0);
    pstTm = localtime(&now);

可以根据需要在本文件或者头文件中加上开关宏来决定到底将消息写到哪里:   文件 还是 标准输出  

//ifndef REP  -----------define REP  ----------#endif   这个预处理 REP 是宏定义 只是没有值

#ifndef REP
    stream = stdout;
#else
    stream = fopen(REP_LOG_FILE, "a+");
#endif


    fprintf(stream, "%04d-%02d-%02d, %02d:%02d:%02d, ", pstTm->tm_year + 1900, pstTm->tm_mon, pstTm->tm_mday, pstTm->tm_hour, pstTm->tm_min, pstTm->tm_sec);
    fprintf(stream, "%s, %s, L%d:\r\n", szFunction, szFile, iLine);
    fprintf(stream, "%s\r\n", acDebugBuffer);
    if(errno != 0)
    {
        fprintf(stream, "Err(%d): %s.\r\n", errno, strerror(errno));
    }
    fprintf(stream, "\r\n");
    errno = 0;

#ifndef REP
    fflush(stream);
#else
    fclose(stream);
#endif


    return;
}

int REP_Printf(const char *pcFmt, ...)
{
    char acBuffer[REP_DEBUG_BUFFER_SIZE];
    int iLen;
    va_list args;
    FILE *stream;


    va_start(args, pcFmt);
    iLen = repVsprintf(acBuffer, pcFmt, args);
    va_end(args);


#ifndef REP
    stream = stdout;
#else
    stream = fopen(REP_LOG_FILE, "a+");
#endif
    fprintf(stream, acBuffer);



#ifndef REP
    fflush(stream);
#else
    fclose(stream);
#endif


    return iLen;
}

#ifdef __cplusplus
}
#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值