linux c log 日志接口


 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM