logger.hpp 989 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #ifndef __LOGGER_HPP__
  2. #define __LOGGER_HPP__
  3. #include <cstdio>
  4. #include <time.h>
  5. /*日志等级*/
  6. enum {
  7. NORMAL,
  8. DEBUG,
  9. ERROR,
  10. FATAL
  11. };
  12. /*将日志等级转化为字符串*/
  13. const char* level_to_stirng(int level) {
  14. switch (level)
  15. {
  16. case NORMAL:
  17. return "NORMAL";
  18. case DEBUG:
  19. return "DEBUG";
  20. case ERROR:
  21. return "ERROR";
  22. case FATAL:
  23. return "FATAL";
  24. default:
  25. return nullptr;
  26. }
  27. }
  28. #define LOG(level, format, ...) do {\
  29. const char* levelstr = level_to_stirng(level); /*日志等级*/\
  30. time_t ts = time(NULL); /*时间戳*/\
  31. struct tm *lt = localtime(&ts); /*格式化时间*/\
  32. char buffer[32] = { 0 };\
  33. strftime(buffer, sizeof(buffer) - 1, "%y-%m-%d %H:%M:%S", lt); /*格式化时间到字符串*/\
  34. fprintf(stdout, "[%s][%s][%s:%d] " format "\n", levelstr, buffer, __FILE__, __LINE__, ##__VA_ARGS__); /*##解除必须传递可变参数的限制*/\
  35. } while(0)
  36. #endif