讲师中心 微信公众号
AI工具推荐 视频效率加速

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

浅伟酱_6851

浅伟酱_6851

发布时间:2025-09-04 08:16:20

|

1027人浏览过

|

来源于php中文网

原创

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

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

spdlog 的特性包括:

(1) 速度极快,性能是其主要目标;

(2) 仅包含头文件,方便使用;

(3) 日志格式化处理使用开源的 fmt 库(https://www.php.cn/link/02251d47085ed33996c248c852dd3fa3);

(4) 可选地支持 printf 语法;

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

(6) 支持自定义格式;

(7) 支持条件日志;

Java调试
Java调试

通过 JDWP 实现 Java 远程调试:连接远程 JVM、设置断点、单步执行代码、查看变量值、获取调用栈。适用于需要调试远程 Java 应用、排查运行时状态、追踪代码执行流程的场景。 术语注解 JDWP:Java Debug Wire Protocol,Java 调试有线协议(Java 远程调试底层通信协议) remote JVM:远程 Java 虚拟机 step through code:代码单步调试(步入 / 步过 / 步出调试) inspect variables:变量查看 / 变量检视 stac

下载

(8) 支持多线程和单线程日志;

(9) 多种日志目标:可对日志文件进行循环输出;可每日生成日志文件;支持控制台日志输出(支持颜色);系统日志;Windows 调试器;易于扩展自定义日志目标;

(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("{");
        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 initialization failed: " << ex.what() << std::endl;
    }
    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;
    explicit my_type(int a):i(a){}
};
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 {
        auto console = spd::stdout_color_mt("console");
        console->info("user defined type: {}", my_type{ 14 });
    } catch (const spd::spdlog_ex& ex) {
        std::cout << "Log initialization failed: " << ex.what() << std::endl;
    }
    return 0;
}
// error handling (can be set globally or per logger(using spdlog::logger::set_error_handler(..))
spdlog::set_error_handler([](const std::string& msg){std::cerr << "*** spdlog error: " << msg << " ***" << std::endl;});
int test_spdlog_error_handling(){
    try {
        auto console = spd::stdout_color_mt("console");
        console->info("some invalid message to trigger an error {}{}{}{}", 3);
    } catch (const spd::spdlog_ex& ex) {
        std::cout << "Log initialization failed: " << ex.what() << std::endl;
    }
    return 0;
}

执行结果如下:

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

GitHub: https://www.php.cn/link/df236b5b4ec12e88f2cb714b641b8cc4

发布者:全栈程序员栈长,转载请注明出处:https://www.php.cn/link/06ac68cc0db1c6c3992eb55812168e55

原文链接:https://www.php.cn/link/c8377ad2a50fb65de28b11cfc628d75c

热门AI工具

更多
蛙蛙写作

一款AI论文写作工具,主要用于超级AI智能写作助手,适合需要提升相关任务效率的用户。

SkildArt
SkildArt Hot

SkildArt是一款AI文本写作工具,一站式 AI 视觉创作平台。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

PixPix
PixPix Hot

PixPix是一款面向电商视觉生产的AI商品图生成工具。

Loomy
Loomy Hot

一款AI工具,主要用于科大讯飞发布的桌面级 AI 助理,比 OpenClaw 更易用、更安全!,适合需要提升相关任务效率的用户。

小橡皮AI

一款AI工具,主要用于小橡皮一键去AI味,将机器味重的内容改得更有活人感,防止因为 AI 内容被平台打上 AI 标签,以及限流,适合需要提升相关任务效率的用户。

UP简历
UP简历 Hot

一款AI办公效率工具,主要用于基于AI技术的免费在线简历制作工具,适合需要提升相关任务效率的用户。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

相关专题

更多
printf用法大全
printf用法大全

php中文网为大家提供printf用法大全,以及其他printf函数的相关文章、相关下载资源以及各种相关课程,供大家免费下载体验。

908

2023.06.20

fprintf和printf的区别
fprintf和printf的区别

fprintf和printf的区别在于输出的目标不同,printf输出到标准输出流,而fprintf输出到指定的文件流。根据需要选择合适的函数来进行输出操作。更多关于fprintf和printf的相关文章详情请看本专题下面的文章。php中文网欢迎大家前来学习。

1029

2023.11.28

堆和栈的区别
堆和栈的区别

堆和栈的区别:1、内存分配方式不同;2、大小不同;3、数据访问方式不同;4、数据的生命周期。本专题为大家提供堆和栈的区别的相关的文章、下载、课程内容,供大家免费下载体验。

6647

2023.07.18

堆和栈区别
堆和栈区别

堆(Heap)和栈(Stack)是计算机中两种常见的内存分配机制。它们在内存管理的方式、分配方式以及使用场景上有很大的区别。本文将详细介绍堆和栈的特点、区别以及各自的使用场景。php中文网给大家带来了相关的教程以及文章欢迎大家前来学习阅读。

2748

2023.08.10

线程和进程的区别
线程和进程的区别

线程和进程的区别:线程是进程的一部分,用于实现并发和并行操作,而线程共享进程的资源,通信更方便快捷,切换开销较小。本专题为大家提供线程和进程区别相关的各种文章、以及下载和课程。

4658

2023.08.10

Python 多线程与异步编程实战
Python 多线程与异步编程实战

本专题系统讲解 Python 多线程与异步编程的核心概念与实战技巧,包括 threading 模块基础、线程同步机制、GIL 原理、asyncio 异步任务管理、协程与事件循环、任务调度与异常处理。通过实战示例,帮助学习者掌握 如何构建高性能、多任务并发的 Python 应用。

1309

2025.12.24

java多线程相关教程合集
java多线程相关教程合集

本专题整合了java多线程相关教程,阅读专题下面的文章了解更多详细内容。

443

2026.01.21

C++多线程相关合集
C++多线程相关合集

本专题整合了C++多线程相关教程,阅读专题下面的的文章了解更多详细内容。

579

2026.01.21

DBeaver怎么导入数据
DBeaver怎么导入数据

DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。

20

2026.11.05

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Uvicorn官方部署指南
Uvicorn官方部署指南

共0课时 | 0人学习

CSS3 教程
CSS3 教程

共18课时 | 16.7万人学习

JavaScript ES5基础线上课程教学
JavaScript ES5基础线上课程教学

共6课时 | 12.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn