spdlog是一个开源的且只需要头文件即可使用的跨平台日志库,适用于c++11版本。
1.安装步骤
# 1.源码下载
git clone https://github.com/gabime/spdlog
# 2.拷贝头文件
cp -rf spdlog/include/spdlog /usr/include/
2.使用举例
测试代码如下:
#include <iostream>
#include <memory>
#include <string>
#include "spdlog/spdlog.h"
#include "spdlog/sinks/daily_file_sink.h"
using namespace std;
/*
* 日志级别
* trace 0
* debug 1
* info 2
* warn 3
* error 4
* critical 5
*/
int main()
{
// 创建文件名类似于: daily_log_2020_05-28.txt,如果程序不退出的话,就是每天2:30 am创建新的文件
auto logger = spdlog::daily_logger_mt("spdlog", "daily_log.txt", 2, 20);
// 设置日志级别,默认是info
spdlog::set_level(spdlog::level::trace);
// 写入log文件
string s="success";
logger->info("test s ={}",s); //{}可以表示变量,跟printf的语法类似
logger->trace("this is trace log");
logger->debug("this is debug log");
logger->info("this is info log");
logger->warn("this is warning log");
logger->error("this is a error log");
logger->critical("this is critical log");
cout << "success" << endl; //控制台输出
return 0;
}
编译测试结果如下:
[root@centos7 spdlog_test]# g++ -std=c++11 -g log_test.cpp -o log_test
[root@centos7 spdlog_test]# ./log_test
success
[root@centos7 spdlog_test]# cat daily_log_2023-01-14.txt
[2023-01-14 19:34:44.418] [spdlog] [info] test s =success
[2023-01-14 19:34:44.418] [spdlog] [trace] this is trace log
[2023-01-14 19:34:44.418] [spdlog] [debug] this is debug log
[2023-01-14 19:34:44.418] [spdlog] [info] this is info log
[2023-01-14 19:34:44.418] [spdlog] [warning] this is warning log
[2023-01-14 19:34:44.418] [spdlog] [error] this is a error log
[2023-01-14 19:34:44.418] [spdlog] [critical] this is critical log