C++linux下使用clog和重定向實現寫日志
- 實現文件
- 基本功能
- 測試
- 編譯
- 運行
- 額外知識點
實現文件
LogUtil.hpp
/**
* 通用日志實現
* lsl
* 2024-06-04
*/#ifndef LOGUTIL_HPP
#define LOGUTIL_HPP
#include<iostream>
#include <time.h>
#include <cstring>
#define __FILENAME__ (strrchr(__FILE__, '/') ? (strrchr(__FILE__, '/') + 1):__FILE__)
char* __DATETIME__(){ char format[32]="%Y-%m-%d %X";time_t tt = time(NULL);struct tm ltm;localtime_r(&tt, <m);char*s=new char[32];strftime(s, 32, format, <m);return s; };
#define LogInfo(msg) (std::clog<<"["<<__DATETIME__()<<"][INFO]["<<__FILENAME__<<"]["<<__FUNCTION__<<":"<<__LINE__<<"] "<<msg<<std::endl)
#define LogWarn(msg) (std::clog<<"["<<__DATETIME__()<<"][WARN]["<<__FILENAME__<<"]["<<__FUNCTION__<<":"<<__LINE__<<"] "<<msg<<std::endl)
#define LogError(msg) (std::clog<<"["<<__DATETIME__()<<"][ERROR]["<<__FILENAME__<<"]["<<__FUNCTION__<<":"<<__LINE__<<"] "<<msg<<std::endl)
#endif // LOGUTIL_HPP
基本功能
三種日志類型,INFO,WARN,ERROR
日志攜帶日期時間
日志攜帶文件名、函數名和日志所在行。
測試
prog1.cc
#include<LogUtil.hpp>
int main(){LogInfo("測試"<<11<<"hahah ");LogWarn("測試2"<<11<<"hahah ");LogError("測試3"<<11<<"hahah ");return 0;
}
編譯
g++ prog1.cc LogUtil.hpp -I./ -o logutil
運行
./logutil &>log_20240604.log
[root@localhost myPractice]# ./logutil &>log_20240604.log
[root@localhost myPractice]# cat log_20240604.log
[2024-06-04 18:02:01][INFO][prog1.cc][main:3] 測試11hahah
[2024-06-04 18:02:01][WARN][prog1.cc][main:4] 測試211hahah
[2024-06-04 18:02:01][ERROR][prog1.cc][main:5] 測試311hahah
額外知識點
- main函數是int類型,return 0說明程序正常退出。 通過命令 echo &? 能查看到退出情況。
- 重定向 < 輸入,對應cin, 標準輸出1>,對應cout, 錯誤輸出2>,對應cerr,clog。
- 1>>tt.log 追加輸出, 2>>tt.log, &>>tt.log 所有追加輸出到一個文件。