log库spdlog简介及使用[通俗易懂]

log库spdlog简介及使用[通俗易懂]spdlog是一个开源的、快速的、仅有头文件的C++11日志库,code地址在https://github.com/gabime/spdlog,目前最新的发布版本为0.14.0。它提供了向流、标准输出、文件、系统日志、调试器等目标输出日志的能力。它支持的平台包括Windows、Linux、Mac、Android。spdlog特性:(1)、非常快,性能是它的主要目标;(2)、仅包括…

大家好,又见面了,我是你们的朋友全栈君。

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;
}

执行结果如下:

log库spdlog简介及使用[通俗易懂]

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/152290.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月23日 下午4:00
下一篇 2022年6月23日 下午4:16


相关推荐

  • padStart()微信浏览器不支持

    padStart()微信浏览器不支持记录下今天写微信小程序遇见的问题。在处理后台返回的时间戳时使用了padStart()方法,在手机上中预览都没有问题,便提交了代码,直到在pc端打开小程序时,页面没有数据,随后了解到微信内置内核不支持padStart()方法,所以处理不了数据,才会报错。再转换时间戳可以用uptime2(num){letdate=newDate(num); letdatetime=date.getFullYear() +”-” +((date.getMonth()+1)>

    2025年10月10日
    6
  • Hibernate与Mybatis对比

    Hibernate与Mybatis对比Hibernate 与 Mybatis 对比

    2026年3月19日
    2
  • Java——数组的定义与使用「建议收藏」

    Java——数组的定义与使用「建议收藏」目录1.数组2.数组初始化2.1动态初始化(声明并开辟数组)2.2引用传递的内存分析2.3静态初始化(开辟同时赋值)3.二维数组4.数组与方法互操作5.Java对数组的支持5.1排序:5.2拷贝6.对象数组6.1动态初始化1.数组一组相关类型的变量集合缺点:长度固定,存在越界问题2.数组初始化 2.1动态初始化…

    2022年5月22日
    45
  • 运维监控系列(21)-PromQL内置函数

    运维监控系列(21)-PromQL内置函数职能 abs absent absent over time ceil changes clamp clamp max clamp min day of month day of week days in month delta deriv exp floor histogram quantile holt winters hour idelta increase irate label join label repla

    2026年3月16日
    2
  • python和pycharm以及anaconda的安装顺序_症证病三者之间区别

    python和pycharm以及anaconda的安装顺序_症证病三者之间区别1、致欢迎词我将详细讲述在学Python初期的各种手忙脚乱的问题的解决,通过这些步骤的操作,让你的注意力集中在Python的语法上以及后面利用Python所解决的项目问题上。而我自己作为小白,很不幸的没有错过任何的坑,都跳了进去,所以在这里写下经验贴,一方面希望能给后来的学者能够高效的避开这些坑,另一方面也算是自己的总结与警告。2、内容大纲2.1安装顺序能够使用Python的安装…

    2022年8月28日
    4
  • virtualbox增强功能-VBoxGuestAdditions安装

    virtualbox增强功能-VBoxGuestAdditions安装小白的艰辛历程,记录点点滴滴,聚少成多。1、准备virtualbox增强功能VBoxGuestAdditions.iso默认安装virtualbox时就没有增强功能的iso自行下载VBoxGuestAdditions.iso备用如还是没有可以去官网另外下载http://download.virtualbox.org/virtualbox/5.0.2/VBoxGuestAdditions_5.0.2.iso还可以在VBox工具中添加扩展功能,此处仅使用外部添加。2、在virtualb..

    2022年6月24日
    90

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号