首页 > 其他分享 >spdlog 使用学习笔记

spdlog 使用学习笔记

时间:2023-09-08 18:23:02浏览次数:30  
标签:const log level void 笔记 学习 spdlog logger

spdlog使用学习笔记


部分内容参考了《spdlog使用_CSDN》这篇文章。

1. spdlog简介

github地址:https://github.com/gabime/spdlog

spdlog是一个C++的日志管理工具库。

2. spdlog的安装

2.1. 使用包管理器安装

  • Debian: sudo apt install libspdlog-dev
  • Homebrew: brew install spdlog
  • MacPorts: sudo port install spdlog
  • FreeBSD: pkg install spdlog
  • Fedora: dnf install spdlog
  • Gentoo: emerge dev-libs/spdlog
  • Arch Linux: pacman -S spdlog
  • openSUSE: sudo zypper in spdlog-devel
  • vcpkg: vcpkg install spdlog
  • conan: spdlog/[>=1.4.1]
  • conda: conda install -c conda-forge spdlog
  • build2: depends: spdlog ^1.8.2

2.2. 使用源码安装

$ git clone https://github.com/gabime/spdlog.git
$ cd spdlog && mkdir build && cd build
$ cmake .. && make -j

2.3。 仅使用头文件

spdlog/include目录下的文件拷贝到你的项目中即可。

3. 相关概念

3.1. level_enum

日志级别,定义如下:

enum class level_enum
{
    trace,
    debug,
    info,
    warn,
    err,
    critical,
    off,
};

3.2. sink

日志记录器槽,用于设置日志的输出目的地,如控制台、文件等。

常用函数:

virtual void log(const details::log_msg &msg) = 0; // 记录日志,有logger自动调用
virtual void flush() = 0;                       // 刷新日志
virtual void set_pattern(const std::string &pattern) = 0;   // 设置日志格式
virtual void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) = 0;  // 设置日志格式
void set_level(level::level_enum log_level);    // 设置输出日志的最低级别
level::level_enum level() const;            // 获取日志级别
bool should_log(level::level_enum msg_level) const; // 判断是否需要记录日志

3.3. logger

日志记录器,用于记录日志。一个logger对象中存储有多个sink,当调用logger的日志输出函数时,logger会调用自身存储的所有sink对象的log(log_msg) 函数进行输出。与自带的sink对应,spdlog也自带了几种logger。logger类主要使用的函数包括:

template<typename T>
void trace(const T &msg) // 记录trace级别的日志
{
    log(level::trace, msg);
}

template<typename T>
void debug(const T &msg) // 记录debug级别的日志
{
    log(level::debug, msg);
}

template<typename T>
void info(const T &msg)
{
    log(level::info, msg);
}

template<typename T>
void warn(const T &msg)
{
    log(level::warn, msg);
}

template<typename T>
void error(const T &msg)
{
    log(level::err, msg);
}

template<typename T>
void critical(const T &msg)
{
    log(level::critical, msg);
}


// return true logging is enabled for the given level.
bool should_log(level::level_enum msg_level) const
{
    return msg_level >= level_.load(std::memory_order_relaxed);
}

// return true if backtrace logging is enabled.
bool should_backtrace() const
{
    return tracer_.enabled();
}

void set_level(level::level_enum log_level); // 设置日志级别

level::level_enum level() const;

const std::string &name() const;

// set formatting for the sinks in this logger.
// each sink will get a separate instance of the formatter object.
void set_formatter(std::unique_ptr<formatter> f);

// set formatting for the sinks in this logger.
// equivalent to
//     set_formatter(make_unique<pattern_formatter>(pattern, time_type))
// Note: each sink will get a new instance of a formatter object, replacing the old one.
void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);

// backtrace support.
// efficiently store all debug/trace messages in a circular buffer until needed for debugging.
void enable_backtrace(size_t n_messages);
void disable_backtrace();
void dump_backtrace();

// flush functions
void flush();
void flush_on(level::level_enum log_level);
level::level_enum flush_level() const;

// sinks
const std::vector<sink_ptr> &sinks() const;

std::vector<sink_ptr> &sinks();

// error handler
void set_error_handler(err_handler);

// create new logger with same sinks and configuration.
virtual std::shared_ptr<logger> clone(std::string logger_name);

4. spdlog的使用

4.1. 基本使用

#include "spdlog/spdlog.h"

int main() 
{
    spdlog::info("Welcome to spdlog!");
    spdlog::error("Some error message with arg: {}", 1);
    
    spdlog::warn("Easy padding in numbers like {:08d}", 12);
    spdlog::critical("Support for int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
    spdlog::info("Support for floats {:03.2f}", 1.23456);
    spdlog::info("Positional args are {1} {0}..", "too", "supported");
    spdlog::info("{:<30}", "left aligned");
    
    spdlog::set_level(spdlog::level::debug); // Set global log level to debug
    spdlog::debug("This message should be displayed..");    
    
    // change log pattern
    spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v");
    
    // Compile time log levels
    // define SPDLOG_ACTIVE_LEVEL to desired level
    SPDLOG_TRACE("Some trace message with param {}", 42);
    SPDLOG_DEBUG("Some debug message");
}

编译后会输出的对应内容。

4.2. 输出日志到文件

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

int main() 
{
    // Create basic file logger (not rotated)
    //文件保存在logs/basic-log.txt
    auto my_logger = spdlog::basic_logger_mt("basic_logger", "logs/basic-log.txt");
    my_logger->info("Some log message");
    //my_logger是一个指向logger对象的智能指针,可以直接使用->访问logger的成员函数
}

标签:const,log,level,void,笔记,学习,spdlog,logger
From: https://www.cnblogs.com/BryceAi/p/17688290.html

相关文章

  • 2023-09-08学习记录
    零拷贝疑惑原来8张图,就可以搞懂「零拷贝」了https://www.cnblogs.com/xiaolincoding/p/13719610.html零拷贝(Zero-copy)及其应用详解https://www.jianshu.com/p/193cae9cbf07AIONetty线程模型疑惑面试官:Reactor和Proactor为什么性能高?https://zhuanlan.zhih......
  • 密码协议学习笔记(3):实体认证协议
    基于对称密码的实体认证:对称密码,一次传输,单向认证:Alice与Bob拥有一个共享的对称密钥$k_{A,B}$,某次传输中,Bob要验证对面的通信者是Alice,只需要让Alice发送用该密钥加密的Bob的ID以及时间戳($T_A$)或序列号($SN_A$)(防止重放攻击),如果Bob得到的密文解密后确实是有意义的信......
  • React项目笔记-环境搭建、路由封装(跳转Navigate、懒加载lazy)、模块化样式引入、状态管
    环境准备nodev16.15.0npm8.5.5AntDesignofReact:https://ant.design/docs/react/introduce-cn一,创建项目npminitvite√Projectname:...vite-project-react√Selectaframework:»React√Selectavariant:»TypeScript然后使用vscode打开项目,由于......
  • RabbitMQ 笔记一
    1.RabbitMQ-如何保证消息不丢失1.生产者确认机制RabbitMQ提供了publisherconfirm机制来避免消息发送到MQ过程中丢失。消息发送到MQ以后,会返回一个结果给发送者,表示消息是否处理成功消息失败之后如何处理:1回调方法即时重发2记录日志3保存到数据库然后定时重发,成功发送后即刻删除......
  • Cmockery学习
    什么是cmockery?是一个轻量级的C语言单元测试框架什么是单元测试?单元测试就是测试一个系统的最小实现单元,往往是函数示例解析#include<stdarg.h>#include<stddef.h>#include<setjmp.h>#include<cmockery.h>//测add方法voidtest_add(void**state){ assert_in......
  • open代码学习
    ADC用宏定义c++编译器兼容c程序#ifdef__cplusplusextern"c"{}枚举类型传值typedefenum{CHANNAL_1=1;CHANNAL_2=2;CHANNAL_3=3;}a;voidfunc(ax){xxx}//调用方法如下aa1=CHANNAL_1;func(a1);电源管理......
  • 计算几何训练笔记
    Luogu1452旋转卡壳,注意判一下平行的情况,另外有个比较简介的求凸包方法,就不用分别求上凸壳和下凸壳再合起来了:intis(pointa,pointb){returna.x==b.x?a.y<b.y:a.x<b.x;}#definepd(A,B,C)(cross((C-B),(B-A))>0||(cross((C-B),(B-A))==0&&is(A,B)==is(B,C)))sort(p+1,p+n+......
  • 《PROMPT2MODEL: Generating Deployable Models from Natural Language Instructions
    一、Introduction传统上,从零开始构建一个自然语言处理(NLP)模型是一项重大任务。一个寻求解决新问题的NLP从业者需要定义他们的任务范围,找到或创建目标任务领域的行为数据,选择合适的模型架构,训练模型,通过评估评估其性能,然后将其部署到实际应用中。Prompt2Modelisaframeworkfo......
  • CS61B学习日记2
    今天学习了B树和红黑树的概念总结:1.在cs61b中B树分为2-3树和2-3-4树:其中主要的关键点是定L的大小。L是指一个节点最多拥有的元素个数。B树的不变量(我记作为限制):2.1)每个叶子结点到根的路径数相同。2.2)每个包含元素个数为k的非叶子结点,其必有链接k+1个叶子结点2.本课......
  • 安装强化学习包gym报错问题及解决方法
    安装命令pipinstallgymnasium[all]如遇如下报错error:command'swig.exe'failed:Nosuchfileordirectory[endofoutput]note:Thiserrororiginatesfromasubprocess,andislikelynotaproblemwithpip.ERROR:Failedbuildingwheelfo......