commLOG.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "commLOG.h"
  2. //日志的编号
  3. int giInfoNumb = 1;
  4. int debugInfo(char *pLogPath, char *pFile, const char *pFuncName, int iLineNumb, char *fmt, ...)
  5. {
  6. if(NULL == pLogPath ||'\0' == pLogPath[0] || NULL == pFile || '\0' == pFile[0] || NULL == pFuncName ||'\0' == pFuncName[0]){
  7. printf("debugInfo param err:%s,%s,%s,%d\r\n", pLogPath, pFile, pFuncName, iLineNumb);
  8. return LOG_VS_ERR;
  9. }
  10. //判断文件大小是否清空该文件,每1000次写日志里检测1次文件大小
  11. if(0 == (giInfoNumb % 10))
  12. {
  13. struct stat fileStat;
  14. if((giInfoNumb >= LOG_LINE_MAX) || ((0 == stat(pLogPath, &fileStat)) && (fileStat.st_size > LOG_SIZE_MAX))){
  15. printf("\ndebugInfo log too big,%dline,%dbyte\n", giInfoNumb, (int)fileStat.st_size);
  16. remove(pLogPath);
  17. giInfoNumb = 0;
  18. }
  19. }
  20. //写入日期、函数信息
  21. time_t timeSecs = time(NULL);
  22. struct tm *timeInfo = localtime(&timeSecs);
  23. char acTitle[LOG_STR_LEN_1024] = { 0 };
  24. char debugMsg[LOG_STR_LEN_512] = { 0 };
  25. va_list args;
  26. va_start(args, fmt);
  27. vsnprintf(debugMsg, sizeof(debugMsg), fmt, args);
  28. va_end(args);
  29. #if 0
  30. snprintf(acTitle, sizeof(acTitle), "[%04d] [%d%02d%02d/%02d:%02d:%02d] [%s] [%s:%d] %s\n", giInfoNumb++,
  31. timeInfo->tm_year + 1900, timeInfo->tm_mon + 1, timeInfo->tm_mday,
  32. timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec, pFile, pFuncName, iLineNumb,
  33. acTitle);
  34. #else
  35. //节约空间
  36. snprintf(acTitle, sizeof(acTitle), "%02d %02d/%02d:%02d:%02d %s\n", giInfoNumb++,
  37. timeInfo->tm_mday,timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec,
  38. debugMsg);
  39. #endif
  40. //调试打印
  41. printf(acTitle);
  42. //打开文件,写入日志
  43. FILE *pLogHandle = fopen(pLogPath, "a+");
  44. if(NULL == pLogHandle){
  45. printf("ERROR,debugInfo:fopen=%s\n",strerror(errno));
  46. return LOG_VS_ERR;
  47. }
  48. int iLen = strlen(acTitle);
  49. fwrite(acTitle, iLen, 1, pLogHandle);
  50. fclose(pLogHandle);
  51. return LOG_VS_OK;
  52. }