1 #define SIZE_16M 16777216 //1024*1024*16
2 #define LOG_FILE_PATH "./mylog.txt" //日志文件路径
3 #define LOG_PARAMS LOG_FILE_PATH,__FILE__,__func__,__LINE__ //日志文件路径 调用函数所在文件 调用函数名 调用debugInfo时所在行号
4
5 //显示调用debugInfo接口的函数所在的文件名、函数名、行号
6 int debugInfo(char *pLogPath, char *pFile, const char *pFuncName, int iLineNumb, char *fmt, ...);
7
8 //调用举例: 9 debuInfo(LOG_PARAMS, “some string %s, some int %d and so on", "hello log", 101);
10
11 //日志的编号
12 int giInfoNumb = 1;
13 int debugInfo(char *pLogPath, char *pFile, const char *pFuncName, int iLineNumb, char *fmt, ...)
14 {
15 if(NULL == pLogPath ||'\0' == pLogPath[0] || NULL == pFile || '\0' == pFile[0] || NULL == pFuncName ||'\0' == pFuncName[0])
16 return VS_ERR;
17 //判断文件大小是否清空该文件,每1000次写日志里检测1次文件大小
18 if(0 == (giInfoNumb % 1000))
19 {
20 struct stat fileStat;
21 if(0 == stat(pLogPath, &fileStat) && fileStat.st_size > SIZE_16M)
22 remove(pLogPath);
23 }
24 //打开文件,写入日志
25 FILE *pLogHandle = fopen(pLogPath, "a+");
26 if(NULL == pLogHandle)
27 return VS_ERR;
28 //写入日期、函数信息
29 time_t timeSecs = time(NULL);
30 struct tm *timeInfo = localtime(&timeSecs);
31 char acTitle[STR_LEN_2048] = { 0 };
32 snprintf(acTitle, sizeof(acTitle), "[%04d] [%d%02d%02d/%02d:%02d:%02d] [%s] [%s:%d]\n", giInfoNumb++,
33 timeInfo->tm_year + 1900, timeInfo->tm_mon + 1, timeInfo->tm_mday,
34 timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec, pFile, pFuncName, iLineNumb);
35 int iLen = strlen(acTitle);
36 fwrite(acTitle, iLen, 1, pLogHandle);
37 //写入日志
38 fwrite("\t\t\t", 3, 1, pLogHandle);
39 memset(acTitle, 0, sizeof(acTitle));
40 va_list args;
41 va_start(args, fmt);
42 vsnprintf(acTitle, sizeof(acTitle), fmt, args);
43 va_end(args);
44 iLen = strlen(acTitle);
45 fwrite(acTitle, iLen, 1, pLogHandle);
46 fwrite("\n", 1, 1, pLogHandle);
47 //关闭日志文件
48 fclose(pLogHandle);
49 return VS_OK;
50 }