spdlog为C++高效多线程日志库,可以选择header-only或者静态库链接。
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/spdlog.h"
class LOG {
public:
//配置日志文件、写入模式
LOG() {
//日志实例名、日志文件最大大小、滚动文件数量(日志太多的时候,当前文件重命名_1,_2,_3.再写新的文件)
auto logger = spdlog::rotating_logger_mt("log", "log/Srio.txt", 2 * 1024 * 1024, 3);
//格式设置:[年月日 时分秒毫秒] [logger实例名] [日志等级缩写] [线程ID] 日志正文
logger->set_pattern("[%Y-%m-%d %T.%e] [%n] [%L] [thread %t] %v");
//遇到info级别,立马将缓存的buffer写到文件中
spdlog::flush_on(spdlog::level::info);
spdlog::get("log")->set_level(spdlog::level::debug);
}
~LOG() {
spdlog::get("log")->flush();
}
};
//起始函数
{
//用于初始化
static LOG log;
...
}
创建名为log的日志模块,不同日志模块可以使用不同配置。
//BoardCaptureImpl.cpp
#include "spdlog/spdlog.h"
#define DEBUG(x) spdlog::get("log")->debug("[{}] {}", "BoardCaptureImpl", x)
#define INFO(x) spdlog::get("log")->info("[{}] {}", "BoardCaptureImpl", x)
#define SPDERROR(x) spdlog::get("log")->error("[{}] {}", "BoardCaptureImpl", x)
{
//使用示例
DEBUG("Srio open.");
//格式化字符串
INFO(fmt::format("snapshot is called with path={}", std::string(path)));
}
//Display.cpp
#include "spdlog/spdlog.h"
#define DEBUG(x, id) spdlog::get("log")->debug("[{}] {} channelId={}", "display", x, id);
#define INFO(x, id) spdlog::get("log")->info("[{}] {} channelId={}", "display", x, id);
#define SPDERROR(x, id) spdlog::get("log")->error("[{}] {} channelId={}", "display", x, id);
...
不同源文件使用不同宏定义,使用更方便。
详细介绍:
1、基础用法(不写入文件):
spdlog::info("Welcome to spdlog!");
spdlog::debug("Level {}", x);//x为变量
2、设置打印格式:
在使用spdlog时,一般都需要按照需求去设置输出日志的打印格式,例如:
- 时间 YYYY-MM-DD HH:MM:SS显示;
- 日志等级(track,info,debug)是否打印;
- 多线程调试时打印线程ID。
函数原型:spdlog::void set_pattern(const std::string &);
//格式设置:[年月日 时分秒毫秒] [logger实例名] [日志等级缩写] [线程ID] 日志正文
spdlog::get("log")->set_pattern("[%Y-%m-%d %T.%e] [%n] [%L] [thread %t] %v");
重要格式
format | explain | e.g. |
---|---|---|
%n | logger_name | 创建logger时填入的名称 |
%l | log_level | info,debug,track,error |
%L | short log_level 简写的日志等级 | I,D,T,E |
%t | threadID | 线程ID |
%v | messageContent | 日志正文 |
其他格式:
https://blog.csdn.net/shizheng163/article/details/79418190
spdlog下载地址:
https://github.com/gabime/spdlog/tree/v1.x/include/spdlog
参考:
https://blog.csdn.net/yanxiaobugyunsan/article/details/79088533