log日志写法

23 篇文章 0 订阅
#define LOG_FILE                            "./log.txt"
#define MAX_LOG_SIZE                        20971520      //20M
#define G_LOG(fmt, ...)                     g_mylog(__FILE__, __LINE__, __FUNCTION__,  fmt, ##__VA_ARGS__)      //LOG日志宏定义

//声明
gint g_mylog (const gchar* file, gint line, const gchar* function, gchar* fmt, ...);

//实现
gint g_mylog (const gchar* file, gint line, const gchar* function, gchar* fmt, ...)
{
    va_list arg;
    char    pre[128], tmp[1024];
    long    clock;
    struct  tm *c_ptr;
    FILE    *fp;
    struct  stat statbuff;

    time( &clock );
    c_ptr = localtime(&clock);

    sprintf(pre, "[%04d-%02d-%02d %02d:%02d:%02d][%s:%d:%s()]",
         c_ptr->tm_year+1900, c_ptr->tm_mon+1, c_ptr->tm_mday,
         c_ptr->tm_hour, c_ptr->tm_min, c_ptr->tm_sec, file, line , function);

    va_start(arg, fmt);
    vsprintf(tmp, fmt, arg);
    va_end (arg);

    if(!(fp = fopen(LOG_FILE, "at")))   //以追加方式打开文件,不存在则创建
        return -1;

    fprintf(fp, "%s %s\n", pre, tmp);

    fstat(fileno(fp), &statbuff);
    if (statbuff.st_size > MAX_LOG_SIZE)    //如果文件超过规定大小,则保存为back文件
    {
        char path[1024];

        fclose(fp);

        sprintf(path,"cp %s %s_bak", LOG_FILE, LOG_FILE);
        system(path);

        sprintf(path,"rm %s", LOG_FILE);
        system(path);
    }
    else
    {
        fclose(fp);
    }

    return 0;
}



//用法
G_LOG("test1, %d", 8899);
G_LOG("test2");


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值