log_helper.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef AM_LOG
  2. #define AM_LOG
  3. #include <stdio.h>
  4. #include <sys\timeb.h>
  5. #include <time.h>
  6. #include <windows.h>
  7. class AMLog
  8. {
  9. public:
  10. ~AMLog();
  11. static AMLog* get(const char* path = NULL);
  12. void printf(const char* format, ...);
  13. private:
  14. AMLog(FILE* handle);
  15. private:
  16. static AMLog* _log;
  17. FILE* _handle;
  18. };
  19. enum AM_LOG_TYPE {
  20. AL_TYPE_DEBUG = 0,
  21. AL_TYPE_INFO,
  22. AL_TYPE_WARN,
  23. AL_TYPE_ERROR,
  24. AL_TYPE_FATAL,
  25. };
  26. static const char* AM_LOG_STR[] = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"};
  27. #define al_printf(type, format, datetime, ms, ...) \
  28. printf("%s-%.3d [%s] [%s(%d)] " format "\n", \
  29. datetime, \
  30. ms, \
  31. type, \
  32. __FUNCTION__, \
  33. __LINE__, \
  34. ##__VA_ARGS__)
  35. #define PRINT_LINE(type, format, datetime, ms, ...) \
  36. printf("%s-%.3d [%s] [%s(%d)] " format "\n", \
  37. datetime, \
  38. ms, \
  39. type, \
  40. __FUNCTION__, \
  41. __LINE__, \
  42. ##__VA_ARGS__)
  43. #define al_log(type, format, ...) \
  44. do { \
  45. struct _timeb now; \
  46. struct tm today; \
  47. char datetime_str[20]; \
  48. _ftime_s(&now); \
  49. localtime_s(&today, &now.time); \
  50. strftime(datetime_str, 20, "%Y-%m-%d %H:%M:%S", &today); \
  51. AMLog* am_log = AMLog::get(); \
  52. if (am_log) { \
  53. am_log->PRINT_LINE(AM_LOG_STR[type], format, datetime_str, now.millitm, ##__VA_ARGS__); \
  54. } else { \
  55. al_printf(AM_LOG_STR[type], format, datetime_str, now.millitm, ##__VA_ARGS__); \
  56. } \
  57. } while (0)
  58. #define al_debug(format, ...) al_log(AL_TYPE_DEBUG, format, ##__VA_ARGS__)
  59. #define al_info(format, ...) al_log(AL_TYPE_INFO, format, ##__VA_ARGS__)
  60. #define al_warn(format, ...) al_log(AL_TYPE_WARN, format, ##__VA_ARGS__)
  61. #define al_error(format, ...) al_log(AL_TYPE_ERROR, format, ##__VA_ARGS__)
  62. #define al_fatal(format, ...) al_log(AL_TYPE_FATAL, format, ##__VA_ARGS__)
  63. #endif