spdlog庫滿足我的需求:
- 支持windows平台
- 支持unicode
- 日志超過指定大小會自動新建
- c++
其他log庫遇到的問題:
1、NanoLog
c++11版本,重啟程序會覆蓋原有日志內容,而且時間戳是1970年。如果您知道怎么設置請留言。
c++17版本,不支持windows。
2、fmtlog
不知道怎么指定日志大小超過一定值時自動新建日志😭。
3、QsLog
不支持 \n 換行。如果您知道怎么換行請留言。
【spdlog配置】
1、生成 lib
下載后解壓,文件夾處鼠標右鍵,用VSCode打開,會自動彈出選擇編譯器,選擇后自動在build文件夾中編譯出sln。
VS打開sln(我的是VS2019),將spdlog設為啟動項,先別生成、先別生成、先別生成……
做一件很重要的事:項目——屬性,如下圖設置,否則Unicode項目出錯。
此時生成即可。debug、release各生成一次。
2、將用到的放一起
用到的是解壓文件里的include和編譯生成的lib,其他可以刪除。
【spdlog使用】
#include<spdlog/spdlog.h> #include<spdlog/sinks/basic_file_sink.h> //for basic_logger_mt #include<spdlog/sinks/rotating_file_sink.h> //for rotating_logger_mt int main() { //輸出到文件 auto basicLog=spdlog::basic_logger_mt("相機模塊跟蹤","logs/basic-log.txt", false);//false不覆蓋,即append方式。否則每次重啟軟件內容會覆蓋。 auto rotatLog=spdlog::rotating_logger_mt("圖像模塊跟蹤", "logs/rotating.txt", 1024, 3);//超過1K則拆分,最多3個舊日志 auto rotatLog2 = spdlog::rotating_logger_mt("數據庫模塊跟蹤", "logs/rotating2.txt", 1024*1024*5, 20);//一般夠用了,5M、最多20個舊日志 //之后的信息會立刻寫入 spdlog::flush_on(spdlog::level::info); //立刻寫入≥info的,而不是程序關閉才寫入 for (int n = 0; n < 500; ++n) { basicLog->info("中文支持\n換行支持"); basicLog->error("error等級的信息"); rotatLog->info("超過1K則新建文件"); rotatLog2->info("超過5M則新建文件"); } //輸出到終端 spdlog::info("中文支持\n換行支持"); std::string str = "std標准庫\n字符串"; int i = 3; float f = 3.1415; double doub = 2.414; spdlog::info("{0}, {1}, {2}, {3}", str, i, f, doub); spdlog::info("四位整數{:04d}", i); spdlog::info("保留兩位小數{:.2f}", f); //其他知識 spdlog::debug("不會輸出,默認info等級。等級順序debug、info、warn、error、critical"); spdlog::info("Welcome to spdlog!"); spdlog::error("Some error message with arg: {}", 1); spdlog::warn("Easy padding in numbers like {:08d}", 12); spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42); spdlog::info("Support for floats {:06.2f}", 12.123456); spdlog::info("Positional args are {1} {0}..", "too", "supported"); spdlog::info("{:<3}", "left aligned"); spdlog::set_level(spdlog::level::debug); //等級設置 spdlog::debug("此時可以輸出"); spdlog::shutdown(); //釋放 }
【以日期新建文件夾】用於日志存放
基於qt
//新建日志文件夾,logs/年月日 QDateTime currentTime = QDateTime::currentDateTime(); QString currentDateDir = "logs/"+currentTime.toString("yyyyMMdd"); QDir dir; if (!dir.exists(currentDateDir)) { dir.mkdir(currentDateDir); } //新建日志 std::shared_ptr<spdlog::logger> rotateLog; rotateLog = spdlog::rotating_logger_mt("信息跟蹤", currentDateDir.toStdString()+"/log.txt", 1024 * 1024 * 5, 20);//一般夠用了,5M、最多20個舊日志 spdlog::flush_on(spdlog::level::info); //之后的信息(≥info)會立刻寫入