spdlog快速集成
采用 header only 的方案:
基础配置
CMakeLists.txt 文件如下:
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)
cmake_minimum_required(VERSION 3.11)
project(spdlog_examples CXX)
# 定义 spdlog 为 header-only 接口库
add_library(spdlog_header_only INTERFACE)
target_include_directories(spdlog_header_only INTERFACE
${CMAKE_SOURCE_DIR}/third_party
)
add_executable(app src/main.cpp)
target_link_libraries(app PRIVATE spdlog_header_only)
文件分布:
~/project/test/logtest/
├── CMakeLists.txt
├── third_party/
│ └── spdlog/
│ └── spdlog.h ← 头文件直接在这里
├── src/
│ └── main.cpp
└── build/
spdlog.h 怎么获取呢?
main.cpp
#include <spdlog/spdlog.h>
int main()
{
spdlog::info("Welcome to spdlog version {}.{}.{} !", SPDLOG_VER_MAJOR, SPDLOG_VER_MINOR,
SPDLOG_VER_PATCH);
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("{:>8} aligned, {:<8} aligned", "right", "left");
// Runtime log levels
spdlog::set_level(spdlog::level::info); // Set global log level to info
spdlog::debug("This message should not be displayed!");
spdlog::set_level(spdlog::level::trace); // Set specific logger's log level
spdlog::debug("This message should be displayed..");
// Customize msg format for all loggers
spdlog::set_pattern("[%H:%M:%S %z] [%^%L%$] [thread %t] %v");
spdlog::info("This an info message with custom format");
spdlog::set_pattern("%+"); // back to default format
spdlog::set_level(spdlog::level::info);
// Backtrace support
// Loggers can store in a ring buffer all messages (including debug/trace) for later
// inspection. When needed, call dump_backtrace() to see what happened:
spdlog::enable_backtrace(10); // create ring buffer with capacity of 10 messages
for (int i = 0; i < 100; i++)
{
spdlog::debug("Backtrace message {}", i); // not logged..
}
// e.g. if some error happened:
spdlog::dump_backtrace(); // log them now!
return 0;
}
配置可以自动保存log的方式
在 main.cpp 中设置好 default logger 后,其他文件直接 #include 就能用:
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/rotating_file_sink.h>
int main() {
// 创建两个 sink
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
// 文件最大 5MB,最多保留 3 个备份
auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>("app.log", 1024 * 1024 * 5, 3);
// 创建 logger,同时绑定两个 sink
auto logger = std::make_shared<spdlog::logger>("app", spdlog::sinks_init_list{console_sink, file_sink});
spdlog::set_default_logger(logger);
// 设置日志级别
logger->set_level(spdlog::level::debug);
// 使用
spdlog::info("这条日志会同时出现在终端和 app.log 文件中");
spdlog::debug("debug 信息也会同时输出");
return 0;
}
其他.c 用起来就很简单了
// other.cpp
#include <spdlog/spdlog.h>
void doSomething() {
spdlog::info("other 文件也能直接用"); // ← 直接用,自动走 default logger
spdlog::debug("debug 信息");
}

浙公网安备 33010602011771号