Browse Source

添加日志管理

yaozheng0922 4 months ago
parent
commit
3297e6c7b8
1 changed files with 40 additions and 0 deletions
  1. 40 0
      source/logger.hpp

+ 40 - 0
source/logger.hpp

@@ -0,0 +1,40 @@
+#ifndef __LOGGER_HPP__
+#define __LOGGER_HPP__
+#include <cstdio>
+#include <time.h>
+
+/*日志等级*/    
+enum  {
+    NORMAL, 
+    DEBUG, 
+    ERROR,
+    FATAL
+};
+
+/*将日志等级转化为字符串*/
+const char* level_to_stirng(int level) {
+    switch (level)
+    {
+    case NORMAL:
+        return "NORMAL";
+    case DEBUG:
+        return "DEBUG";
+    case ERROR:
+        return "ERROR";
+    case FATAL:
+        return "FATAL";
+    default:
+        return nullptr;
+    }
+}
+
+#define LOG(level, format, ...) do {\
+    const char* levelstr = level_to_stirng(level); /*日志等级*/\
+    time_t ts = time(NULL);  /*时间戳*/\  
+    struct tm *lt = localtime(&ts);  /*格式化时间*/\ 
+    char buffer[32] = { 0 };\
+    strftime(buffer, sizeof(buffer) - 1, "%y-%m-%d %H:%M:%S", lt);  /*格式化时间到字符串*/\
+    fprintf(stdout, "[%s][%s][%s:%d] " format "\n", levelstr, buffer, __FILE__, __LINE__, ##__VA_ARGS__); /*##解除必须传递可变参数的限制*/\
+} while(0)
+
+#endif