C++ 格式化日志输出实现代码

时间:2022-01-30 13:37:40

核心代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
void LogOut(LPCTSTR pFormat, ...)
{
  char LogFile[128]={0};
  char str[1024]={0};
  FILE** fp=&(ThreadDatas[0].pf);
 
  va_list pArg;
 
  EnterCriticalSection(&cs_log);//独占访问
  __try
  {
    SYSTEMTIME st;
    if(ThreadDatas[0].num>100000)//10W条一个文件
    {
      if(fp)
      {
        fclose(*fp);
        *fp=0;
      }
      ThreadDatas[0].num=0;
    }
    if(NULL==*fp)
    {
      char tstr[20]={0};
      //GetSystemTime(&st);
      GetLocalTime(&st);
      sprintf(LogFile,".\\logs\\ASR_%04d-%02d-%02d.%02d_%02d_%02d.log",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
      *fp=fopen(LogFile,"a+");
      if( NULL==*fp )
      {
      //printf("Create LogFile faile %s\n",LogFile);
        LogEvent("Create LogFile faile %s",LogFile);
        return;
      }
      //else
      //LogEvent("Create LogFile %s",LogFile,*fp);
    }
    GetLocalTime(&st);
    sprintf(str,"%04d-%02d-%02d %02d:%02d:%02d.%03d %s",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds,pFormat);
    va_start(pArg, pFormat);
    //fprintf(*fp,chMsg);
    vfprintf(*fp, str, pArg);
    va_end(pArg);
    fflush(*fp);
  }
  __except(EXCEPTION_EXECUTE_HANDLER)
  {
    LogEvent("Thread Log file Error:%s",LogFile);
  }
  LeaveCriticalSection(&cs_log);//释放独占访问
}

好了,这篇文章就结束到这,后续服务器之家小编会为大家提供更多的代码。

原文链接:https://www.cnblogs.com/lzpong/p/3955901.html