博客
关于我
c++日志工具spdLog
阅读量:398 次
发布时间:2019-03-05

本文共 1873 字,大约阅读时间需要 6 分钟。

spdLog 简单使用示例代码

spdLog 是一款流行的 C++ 日志工具,使用非常简单。以下是基于源码修改的测试代码示例。

#include

#include <spdlog/spdlog.h>#include <spdlog/sinks/stdout_color_sinks.h>

void err_handler_example() {spdlog::set_error_handler([](const std::string &msg) {printf("Custom log error handler, %s\n", msg.c_str());});}

int main(int argc, char argv) {try {// 注册并设置默认错误处理器spdlog::set_default_error_handler([](const std::string &msg) {printf("**** spdlog 错误处理器, %s *****\n", msg.c_str());});

// 创建控制台颜色日志输出器     auto console_sink = std::make_shared
(); console_sink->set_level(spdlog::level::debug); console_sink->set_pattern("%^[%Y-%m-%d %H:%M:%S:%e] [%n] [%t] [%l] %v%$"); // 创建旋转文件日志输出器 auto file_sink = std::make_shared
( "logs/multisink.txt", 1048576, 3 ); file_sink->set_level(spdlog::level::debug); file_sink->set_pattern("[%Y-%m-%d %H:%M:%S:%e] [%n] [%t] [%l] %v"); // 创建日志对象,绑定多个输出器 auto logger = std::make_shared
("multi_sink", begin(sinks), end(sinks)); // 设置默认日志级别 logger->set_level(spdlog::level::debug); // 自定义错误处理器 logger->set_error_handler([](const std::string &msg) { printf("*****Custom log error handler, %s*****\n", msg.c_str()); }); // 测试输出 logger->warn("这条信息应该同时出现在控制台和文件中"); logger->info("这条信息应该只出现在文件中"); // 注册日志器 spdlog::register_logger(logger); // 获取已注册的日志器 auto test_logger = spdlog::get("multi_sink"); test_logger->info("获取日志器成功"); // 测试字符串格式化 std::string msg = "你好,spdlog!"; logger->warn("spdlog: {}", msg); // 创建旋转日志器 auto rotating_logger = spdlog::rotating_logger_mt("log_rotating", "logs/rotating.txt", 256, 2); for (int i = 0; i < 10; ++i) { rotating_logger->info("{} * {} 等于 {:>10}", i, i, i * i); } } catch (const spdlog::spdlog_ex &ex) { std::cerr << "日志初始化失败" << ex.what() << std::endl; }

}

转载地址:http://ahgg.baihongyu.com/

你可能感兴趣的文章
Python 中如何实现列表的切片?
查看>>
Python 中如何实现字典的排序?
查看>>
Python 中常用的数据类型及相关操作详解
查看>>
Python 中的离线语音转文本
查看>>
Python 中的线程
查看>>
Python 中的继承机制是什么样的?
查看>>
Python 中的装饰器是什么?
查看>>
Python 中的装饰器是如何工作的,有哪些实际应用场景?
查看>>
python读excel
查看>>
Python 中读取 CSV 文件-ChatGPT4o作答
查看>>
python请求html_使用Python请求获取HTML?
查看>>
Python 之匿名函数和偏函数
查看>>
python 之栈的实现
查看>>
python语音播放
查看>>
python语言:装饰器原理
查看>>
Python 交互式数据可视化详解
查看>>
python语言有哪些优点和缺点_Python有哪些优缺点,你了解吗?
查看>>
Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
查看>>
Python 从数据库中存储和检索密码的最安全方法
查看>>
Python语言及其应用 - 知识点遍历
查看>>