log库spdlog简介及使用

spdlog是一个开源的、快速的、仅有头文件的C++11 日志库,code地址在 https://github.com/gabime/spdlog ,目前最新的发布版本为0.14.0。它提供了向流、标准输出、文件、系统日志、调试器等目标输出日志的能力。它支持的平台包括Windows、Linux、Mac、Android。

spdlog特性:

(1)、非常快,性能是它的主要目标;

(2)、仅包括头文件;

(3)、日志的格式化处理使用开源的fmt库(  https://github.com/fmtlib/fmt );

(4)、可选的printf语法支持;

(5)、非常快的异步模式(可选),支持异步写日志;

(6)、自定义格式;

(7)、条件日志;

(8)、多线程/单线程日志;

(9)、各种日志目标:可对日志文件进行循环输出;可每日生成日志文件;支持控制台日志输出(支持颜色);系统日志;Windows debugger;较容易扩展自定义日志目标;

(10)、支持日志输出级别:阈值级别既可以在运行时也可以在编译时修改。

以下是测试代码,主要来自spdlog/example/example.cpp:

#include "funset.hpp"
#include <iostream>
#include "spdlog/spdlog.h"
#include "spdlog/fmt/ostr.h"

namespace spd = spdlog;

int test_spdlog_console()
{
	try {
		// Console logger with color
		auto console = spd::stdout_color_mt("console");
		console->info("Welcome to spdlog!");
		console->error("Some error message with arg{}..", 1);

		// Conditional logging example
		console->info_if(true, "Welcome to spdlog conditional logging!");

		// Formatting examples
		console->warn("Easy padding in numbers like {:08d}", 12);
		console->critical("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
		console->info("Support for floats {:03.2f}", 1.23456);
		console->info("Positional args are {1} {0}..", "too", "supported");
		console->info("{:<30}", "left aligned");

		SPDLOG_DEBUG_IF(console, true, "This is a debug log");

		spd::get("console")->info("loggers can be retrieved from a global registry using the spdlog::get(logger_name) function");

		// Create basic file logger (not rotated)
		auto my_logger = spd::basic_logger_mt("basic_logger", "E:/GitCode/Messy_Test/testdata/basic_log");
		my_logger->info("Some log message");

		// Create a file rotating logger with 5mb size max and 3 rotated files
		auto rotating_logger = spd::rotating_logger_mt("some_logger_name", "E:/GitCode/Messy_Test/testdata/mylogfile_log", 1048576 * 5, 3);
		for (int i = 0; i < 10; ++i)
			rotating_logger->info("{} * {} equals {:>10}", i, i, i*i);

		// Create a daily logger - a new file is created every day on 2:30am
		auto daily_logger = spd::daily_logger_mt("daily_logger", "E:/GitCode/Messy_Test/testdata/daily_log", 2, 30);
		// trigger flush if the log severity is error or higher
		daily_logger->flush_on(spd::level::err);
		daily_logger->info(123.44);

		// Customize msg format for all messages
		spd::set_pattern("*** [%H:%M:%S %z] [thread %t] %v ***");
		rotating_logger->info("This is another message with custom format");

		// Runtime log levels
		spd::set_level(spd::level::info); //Set global log level to info
		console->debug("This message shold not be displayed!");
		console->set_level(spd::level::debug); // Set specific logger's log level
		console->debug("This message shold be displayed..");

		// Compile time log levels
		// define SPDLOG_DEBUG_ON or SPDLOG_TRACE_ON
		SPDLOG_TRACE(console, "Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}", 1, 3.23);
		SPDLOG_DEBUG(console, "Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}", 1, 3.23);
		SPDLOG_DEBUG_IF(console, true, "This is a debug log");

		// Apply a function on all registered loggers
		spd::apply_all([&](std::shared_ptr<spdlog::logger> l) { l->info("End of example."); });

		// Release and close all loggers
		spdlog::drop_all();
	}
	// Exceptions will only be thrown upon failed logger or sink construction (not during logging)
	catch (const spd::spdlog_ex& ex) {
		std::cout << "Log init failed: " << ex.what() << std::endl;
		return -1;
	}

	return 0;
}

int test_spdlog_async()
{
	// Asynchronous logging is very fast..
	// Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..
	size_t q_size = 4096; //queue size must be power of 2
	spdlog::set_async_mode(q_size);
	auto async_file = spd::daily_logger_st("async_file_logger", "E:/GitCode/Messy_Test/testdata/async_log");

	for (int i = 0; i < 100; ++i)
		async_file->info("Async message #{}", i);

	return 0;
}

int test_spdlog_syslog()
{
	// there is no syslog.h file in windows, so macro SPDLOG_ENABLE_SYSLOG should be disenable
#ifdef SPDLOG_ENABLE_SYSLOG
	std::string ident = "spdlog-example";
	auto syslog_logger = spd::syslog_logger("syslog", ident, LOG_PID);
	syslog_logger->warn("This is warning that will end up in syslog.");
#endif

	return 0;
}

// user defined types logging by implementing operator<<
struct my_type {
	int i;
	template<typename OStream>
	friend OStream& operator<<(OStream& os, const my_type& c)
	{
		return os << "[my_type i=" << c.i << "]";
	}
};

int test_spdlog_user_defined()
{
	try {
		//spd::get("console")->info("user defined type: {}", my_type{ 14 });
		auto console = spd::stdout_color_mt("console");
		console->info("user defined type: {}", my_type{ 14 });
	} catch (const spd::spdlog_ex& ex) {
		std::cout << "user defined log fail: " << ex.what() << std::endl;
		return -1;
	}

	return 0;
}

int test_spdlog_err_handler()
{
	// can be set globaly or per logger(logger->set_error_handler(..))
	spdlog::set_error_handler([](const std::string& msg)
	{
		std::cerr << "my err handler: " << msg << std::endl;
	});

	//spd::get("console")->info("some invalid message to trigger an error {}{}{}{}", 3);
	auto console = spd::stdout_color_mt("console");
	console->info("some invalid message to trigger an error {}{}{}{}", 3);

	return 0;
}

执行结果如下:

GitHub: https://github.com/fengbingchun/Messy_Test

  • 15
    点赞
  • 93
    收藏
    觉得还不错? 一键收藏
  • 26
    评论
使用spdlog,需要按照以下步骤进行设置: 1. 下载spdlog的代码。可以在https://github.com/gabime/spdlog上找到spdlog的代码。 2. 将下载下来的代码解压,并找到其中的include文件夹。该文件夹包含了spdlog所需的头文件和源码。 3. 新建一个C++项目,例如控制台应用程序项目。 4. 打开项目属性页,进入C/C++设置。 5. 在常规选项卡的附加包含目录中,添加spdlog的include文件夹的路径。 6. 在代码中包含spdlog的头文件,例如`#include "spdlog/spdlog.h"`。 7. 可以开始使用spdlog了。以下是一个简单的示例代码,用于在控制台输出日志: ```cpp #include "spdlog/spdlog.h" int main() { // 创建一个名称为"console"的logger,将日志输出到控制台 auto console_logger = spdlog::stdout_logger_mt("console"); // 输出不同级别的日志 console_logger->trace("This is a trace message"); console_logger->debug("This is a debug message"); console_logger->info("This is an info message"); console_logger->warn("This is a warning message"); console_logger->error("This is an error message"); return 0; } ``` 在该示例代码中,我们首先创建了一个名为"console"的logger对象,该对象将日志输出到控制台。然后,我们使用不同的日志级别输出了不同的日志消息。 注意:以上示例只是spdlog的简单用法,还有更多高级用法可以根据需要使用。请参考spdlog的文档和示例代码以了解更多详细信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值