mylog.c 2.8 KB

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