基于spdlog实现日志控制台输出、文件输出或控制台+文件同时输出

基于spdlog封装了一套接口,可实现控制台log输出、文件log输出,或控制台+文件同时输出,根据自己需求自由切换。亲测OK,分享一下。

头文件定义基类HrgLogger和三个子类ConsoleLogger、FileLogger和MultiLogger:

#ifndef __HRG_LOG__
#define __HRG_LOG__

#include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>


#include "spdlog/spdlog.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/logger.h"

#include "spdlog/sinks/stdout_sinks.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/common.h"

enum LoggerMode
{
	LAB_MODE = 0,  //实验室模式,打印比较细致的信息
	TRIAL_MODE = 1,   //试用模式,打印调试信息
	USER_MODE = 2,    //用户模式,打印较重要的信息
};

#define LOG_MODE USER_MODE

using namespace spdlog;

#define LOG_LEVEL_TRACE spdlog::level::trace
#define LOG_LEVEL_DEBUG spdlog::level::debug
#define LOG_LEVEL_INFO spdlog::level::info
#define LOG_LEVEL_WARN spdlog::level::warn
#define LOG_LEVEL_ERROR spdlog::level::err
#define LOG_LEVEL_CRITICAL spdlog::level::critical
#define LOG_LEVEL_OFF spdlog::level::off

using print_level = spdlog::level::level_enum;    //变量重命名
using format_string = string_view_t;      // 变量重命名 //wstring_view_t;   //fmt::basic_string_view<char>;


class HrgLogger
{
public:
	HrgLogger()
	{
		logger_created = false;
		logger_droped = false;
	}
	
	~HrgLogger();
	
	std::shared_ptr<spdlog::logger> hrg_logger;
	
	bool logger_created;         //标识日志创建状态
	bool logger_droped;          //标识日志关闭状态
	time_t logger_create_time;   //日志创建时间

	/* Generate log file name automatically according to real time, usually used when many real-time log files should be output */
	virtual void generate_file_name_automaticaly();

	/* Set a specified log file name, usually used when only one log file is needed.
		input param @filename is the specified filename.
	  */
	void set_specified_file_name(std::string filename);

	/* The abstract api for create logger, would be realized by the derived classes */
	virtual void create_logger() = 0;   //创建logger的纯虚函数,只能在子函数中实现
		
	/* 设置日志的打印级别 */
	void set_print_level(print_level lvl)
	{
		hrg_logger->set_level(lvl);
	}

	/* 重新封装logger的trace, debug, warn, error和critical打印接口 */
	template<typename... Args>
	inline void print_trace(format_string fmt, const Args &... args)
	{
		hrg_logger->trace(fmt, args...);
	}
	
	template<typename... Args>
	inline void print_debug(format_string fmt, const Args &... args)
	{
		hrg_logger->debug(fmt, args...);
	}
	
	template<typename... Args>
	inline void print_info(format_string fmt, const Args &... args)
	{
		hrg_logger->info(fmt, args...);
	}
	
	template<typename... Args>
	inline void print_warn(format_string fmt, const Args &... args)
	{
		hrg_logger->warn(fmt, args...);
	}
	
	template<typename... Args>
	inline void print_error(format_string fmt, const Args &... args)
	{
		hrg_logger->error(fmt, args...);
	}

	template<typename... Args>
	inline void print_critical(format_string fmt, const Args &... args)
	{
		hrg_logger->critical(fmt, args...);
	}
	
	/* 销毁logger */
	void destroy_logger()
	{
		spdlog::drop_all();
		logger_droped = true;
	}
	
protected:
	std::string log_full_name;  //The full name contains log_path and log_file_name
	std::string log_path;  // The log path which is specified in class constructor
	
};

/* 控制台logger子类 */
class ConsoleLogger : public HrgLogger
{
public:
	ConsoleLogger()
	{
		std::cout << "ConsoleLogger constructor.
### 如何在 C++ 项目中使用 Spdlog 日志库 #### 安装与配置 为了在 C++ 项目中集成 Spdlog,首先需要获取该库。由于这是一个仅含头文件的库,安装过相对简单。可以从 GitHub 上克隆仓库者下载压缩包并解压到项目的合适位置[^1]。 对于现代构建系统如 CMake 的使用者来说,在 `CMakeLists.txt` 文件里添加如下指令来引入本地路径下的 Spdlog文件: ```cmake include_directories(path/to/spdlog/include) ``` 如果采用 Conan vcpkg 这样的依赖管理工具,则可以通过这些工具自动拉取最新版本的 Spdlog 库[^2]。 #### 初始化日志记录器 初始化一个简单的控制台日志记录器只需要几行代码即可完成。下面的例子展示了如何创建一个基本的日志实例并向其注册不同的日志级别过滤条件: ```cpp #include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_color_sinks.h" int main() { try { auto console = spdlog::stdout_color_mt("console"); console->set_level(spdlog::level::debug); // 设置最低日志等级为 debug console->info("Welcome to spdlog!"); console->error("Some error message with arg: {}", 1); console->warn("Easy padding in numbers like {:08d}", 12); console->critical("Support for int: {}, double: {:.3f}, and strings too: {}", 42, 3.1415926, "some string"); console->trace("Trace log level is only printed in trace mode."); } catch (const spdlog::spdlog_ex& ex) { std::cout << "Log initialization failed: " << ex.what() << std::endl; } } ``` 这段序会打印不同级别的消息至终端,并且可以根据实际需求调整输出格式和颜色编码等功能[^3]。 #### 配置高级特性 Spdlog 支持丰富的功能集,比如多线环境中的高效性能优化、异步模式下减少阻塞时间以及灵活定制化的日志格式化选项等。通过设置特定参数调用相应 API 可以轻松启用上述提到的功能点[^4]。 例如开启异步模式只需增加一行代码: ```cpp // 启动异步模式,默认队列大小为 1000 条日志条目 spdlog::init_thread_pool(8192, 1); auto async_console = spdlog::daily_logger_st("async_console", "./logs/async_log_", "%H:%M:%S"); async_console->flush_on(spdlog::level::err); ``` 以上介绍了关于怎样将 Spdlog 整合进 C++的方法论和技术细节。希望这能帮助开发者们更便捷地利用这一强大的日志解决方案提升开发效率。
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值