log_helper.h 2.3 KB

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