C++多线程日志库spdlog使用

4 篇文章 0 订阅

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");

重要格式

formatexplaine.g.
%nlogger_name创建logger时填入的名称
%llog_levelinfo,debug,track,error
%Lshort log_level 简写的日志等级I,D,T,E
%tthreadID线程ID
%vmessageContent日志正文

其他格式:
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

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值