log_helper.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. #include <QDebug>
  8. class AMLog
  9. {
  10. public:
  11. ~AMLog();
  12. static AMLog* get(const char* path = NULL);
  13. void printf(const char* format, ...);
  14. private:
  15. AMLog(FILE* handle);
  16. private:
  17. static AMLog* _log;
  18. FILE* _handle;
  19. };
  20. enum AM_LOG_TYPE {
  21. AL_TYPE_DEBUG = 0,
  22. AL_TYPE_INFO,
  23. AL_TYPE_WARN,
  24. AL_TYPE_ERROR,
  25. AL_TYPE_FATAL,
  26. };
  27. static const char* AM_LOG_STR[] = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"};
  28. #define al_printf(type, format, datetime, ms, ...) \
  29. printf("%s-%.3d [%s] [%s(%d)] " format "\n", \
  30. datetime, \
  31. ms, \
  32. type, \
  33. __FUNCTION__, \
  34. __LINE__, \
  35. ##__VA_ARGS__)
  36. #define PRINT_LINE(type, format, datetime, ms, ...) \
  37. printf("%s-%.3d [%s] [%s(%d)] " format "\n", \
  38. datetime, \
  39. ms, \
  40. type, \
  41. __FUNCTION__, \
  42. __LINE__, \
  43. ##__VA_ARGS__)
  44. #define al_log(type, format, ...) \
  45. do { \
  46. struct _timeb now; \
  47. struct tm today; \
  48. char datetime_str[20]; \
  49. _ftime_s(&now); \
  50. localtime_s(&today, &now.time); \
  51. strftime(datetime_str, 20, "%Y-%m-%d %H:%M:%S", &today); \
  52. AMLog* am_log = AMLog::get(); \
  53. if (am_log) { \
  54. char log_buffer[1024]; \
  55. sprintf_s(log_buffer, \
  56. sizeof(log_buffer), \
  57. "%s-%.3d [%s] [%s(%d)] " format "\n", \
  58. datetime_str, \
  59. now.millitm, \
  60. AM_LOG_STR[type], \
  61. __FUNCTION__, \
  62. __LINE__, \
  63. ##__VA_ARGS__); \
  64. am_log->printf("%s", log_buffer); \
  65. qDebug() << QString::fromUtf8(log_buffer); \
  66. } else { \
  67. al_printf(AM_LOG_STR[type], format, datetime_str, now.millitm, ##__VA_ARGS__); \
  68. } \
  69. } while (0)
  70. #define al_debug(format, ...) al_log(AL_TYPE_DEBUG, format, ##__VA_ARGS__)
  71. #define al_info(format, ...) al_log(AL_TYPE_INFO, format, ##__VA_ARGS__)
  72. #define al_warn(format, ...) al_log(AL_TYPE_WARN, format, ##__VA_ARGS__)
  73. #define al_error(format, ...) al_log(AL_TYPE_ERROR, format, ##__VA_ARGS__)
  74. #define al_fatal(format, ...) al_log(AL_TYPE_FATAL, format, ##__VA_ARGS__)
  75. #endif