您的位置:首页 > 编程语言 > C语言/C++

C语言简单写日志函数

2014-12-11 09:52 246 查看
#include <sys/time.h>
#include <stdio.h>
#include <time.h>

/* debug level define */
int g_dbg_level;
FILE *g_log_fp;

/* debug level */
#define DBG_INFOR       0x01  // call information
#define DBG_WARNING     0x02  // paramters invalid,  
#define DBG_ERROR       0x04  // process error, leading to one call fails
#define DBG_CRITICAL    0x08  // process error, leading to voip process can't run exactly or exit

/* debug macro */
#define DBG(level, fmt, para...)    do \
    { \
        time_t t = time(NULL);  \
        struct tm *tmm = localtime(&t); \
        if(g_dbg_level & level)     \
            printf("[%d-%02d-%02d %02d:%02d:%02d][%s][%s:%d]" fmt "\n",tmm->tm_year+1900,tmm->tm_mon+1,tmm->tm_mday,tmm->tm_hour,tmm->tm_min,tmm->tm_sec,__FUNCTION__,__FILE__,__LINE__,##para); \
        if((g_log_fp != NULL) && (level >= DBG_CRITICAL))   \
            fprintf(g_log_fp, "[%d-%02d-%02d %02d:%02d:%02d][%s][%s:%d]" fmt "\n",tmm->tm_year+1900,tmm->tm_mon+1,tmm->tm_mday,tmm->tm_hour,tmm->tm_min,tmm->tm_sec,__FUNCTION__,__FILE__,__LINE__,##para); \
    } while(0)
    
int main()
{
    g_dbg_level = 15;
    g_log_fp = fopen("my_program.log","a+");
    if (g_log_fp == NULL)
    {
        printf("open log file error\n");
    }
    DBG(DBG_INFOR,"hello");
    DBG(DBG_CRITICAL,"hello 222");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: