You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用spdlog在日志文件打开/关闭时打印时间?

在spdlog的文件回调中添加当前时间的实现方法

spdlog提供了直接的时间处理工具,你可以借助它的日志时钟和格式化能力,在after_open和before_close回调中轻松添加当前时间,具体有两种常用实现方式:

方法一:使用spdlog自带的时间格式化工具

spdlog的fmt_helper模块封装了适配日志场景的时间格式化逻辑,能和日志输出的时间风格保持一致:

#include <fmt/core.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/common.h>  // 包含fmt_helper所需定义

int main( )
{
    spdlog::file_event_handlers handlers;

    handlers.after_open = [](const spdlog::filename_t filename, std::FILE* const stream) {
        // 获取spdlog默认日志时钟的当前时间点
        auto now = spdlog::log_clock::now();
        fmt::memory_buffer time_buf;
        // 格式化时间为"年-月-日 时:分:秒"格式,可按需调整
        spdlog::fmt_helper::format_time(time_buf, now, "%Y-%m-%d %H:%M:%S");
        fmt::print(stream, "\n[{}] File '{}': Logging started...\n\n", fmt::to_string(time_buf), filename);
    };

    handlers.before_close = [](const spdlog::filename_t filename, std::FILE* const stream) {
        auto now = spdlog::log_clock::now();
        fmt::memory_buffer time_buf;
        spdlog::fmt_helper::format_time(time_buf, now, "%Y-%m-%d %H:%M:%S");
        fmt::print(stream, "\n[{}] File '{}': Logging finished.\n", fmt::to_string(time_buf), filename);
    };

    auto logger = spdlog::basic_logger_st("basic_logger", "logs/basic-log.txt", true, handlers);
    
    // 测试日志输出
    logger->info("This is a test log message");
    // 手动触发日志器销毁,确保before_close回调执行
    spdlog::drop_all();
}

方法二:直接使用fmt库的chrono格式化功能

如果习惯用fmt原生的时间格式化能力,可借助fmt/chrono模块实现:

#include <fmt/core.h>
#include <fmt/chrono.h>  // 包含chrono时间格式化支持
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <chrono>

int main( )
{
    spdlog::file_event_handlers handlers;

    handlers.after_open = [](const spdlog::filename_t filename, std::FILE* const stream) {
        // 获取系统当前时间
        auto now = std::chrono::system_clock::now();
        // 格式化时间字符串,支持自定义格式
        fmt::print(stream, "\n[{}] File '{}': Logging started...\n\n", 
                   fmt::format("{:%Y-%m-%d %H:%M:%S}", now), filename);
    };

    handlers.before_close = [](const spdlog::filename_t filename, std::FILE* const stream) {
        auto now = std::chrono::system_clock::now();
        fmt::print(stream, "\n[{}] File '{}': Logging finished.\n", 
                   fmt::format("{:%Y-%m-%d %H:%M:%S}", now), filename);
    };

    auto logger = spdlog::basic_logger_st("basic_logger", "logs/basic-log.txt", true, handlers);
    
    logger->info("This is a test log message");
    spdlog::drop_all();
}

补充说明

  • 时间格式字符串可按需调整,比如添加毫秒精度可改为%Y-%m-%d %H:%M:%S.%f;
  • 需调用spdlog::drop_all()或手动销毁日志器,否则程序退出前可能不会触发before_close回调。

内容的提问来源于stack exchange,提问作者digito_evo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:11:09