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 ................