日志访问生成

C语言生成日志,设置文件大小日志文件写满自动从新开始,支持多线程操作。

FILE *flog;
char datestr[16];
char timestr[16];
char mss[4];
pthread_mutex_t cs_log;
void Log(const char *pszFmt,...) {
    va_list argp;

    pthread_mutex_lock(&cs_log);
    va_start(argp,pszFmt);

    struct tm *now;
    struct timeb tb;

    if (NULL==pszFmt||0==pszFmt[0]) return;
    vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
    ftime(&tb);
    now=localtime(&tb.time);
    sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
    sprintf(timestr,"%02d:%02d:%02d",now->tm_hour     ,now->tm_min  ,now->tm_sec );
    sprintf(mss,"%03d",tb.millitm);
    printf("%s %s.%s %s",datestr,timestr,mss,logstr);
    flog=fopen(logfilename,"a");
    if (NULL!=flog)
    {
        fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        if (ftell(flog)>MAXLOGSIZE)
        {
            fclose(flog);
            memset(logfilename,0,100);
            sprintf(logfilename,"%s %s.%s",datestr,timestr,mss);
        } else {
            fclose(flog);
        }
    }else
    {
        sprintf(logfilename,"%s %s.%s",datestr,timestr,mss);
        flog=fopen(logfilename,"a");
        if (NULL!=flog)
        {
            fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
        }
        fclose(flog);
    }
    va_end(argp);
    pthread_mutex_unlock(&cs_log);
}

使用方法:


int main()
{
    pthread_mutex_init(&cs_log,NULL);
    Log("%03d recv %d bytes\n",cn,pb);
    Log("%s\n",binstr);
    pthread_mutex_destroy(&cs_log);
}

效果:

2021-09-27 13:47:06.926 002 recv 2 bytes
2021-09-27 13:47:06.926 002 0000 - 0d 0d                                            ..
2021-09-27 13:47:06.928 002 recv 2 bytes
2021-09-27 13:47:06.928 002 0000 - 0d 0d                                            ..
2021-09-27 13:47:06.930 002 recv 2 bytes
2021-09-27 13:47:06.930 002 0000 - 0d 0d                                            ..
2021-09-27 13:47:06.932 002 recv 2 bytes
2021-09-27 13:47:06.932 002 0000 - 0d 0d                                            ..
2021-09-27 13:47:07.717 001 sent 20 bytes
2021-09-27 13:47:07.717 001 0000 - 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d  ................

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值