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

如何在C++ spdlog封装中输出变量内容?

问题解决方法

核心原因

你当前的调用方式不符合spdlog的格式化规则,且可能存在日志宏封装错误:

  • spdlog要求通过{}作为占位符绑定变量,而非直接用逗号分隔多个参数;
  • 若宏定义未正确转发可变参数,后续变量参数会被忽略。

步骤1:修正日志宏封装(Log.h)

确保宏能正确传递所有参数到spdlog的日志方法:

#pragma once
#include "spdlog/spdlog.h"

namespace Engine {
    class Log {
    public:
        static void Init();
        static std::shared_ptr<spdlog::logger>& GetLogger();
    private:
        static std::shared_ptr<spdlog::logger> s_Logger;
    };
}

// 正确转发可变参数到spdlog的info方法
#define INFO(...) Engine::Log::GetLogger()->info(__VA_ARGS__)
#define WARN(...) Engine::Log::GetLogger()->warn(__VA_ARGS__)
#define ERROR(...) Engine::Log::GetLogger()->error(__VA_ARGS__)

步骤2:修正日志初始化格式(Log.cpp)

确保日志格式包含消息占位符%v,同时设置你需要的前缀样式:

#include "Log.h"
#include "spdlog/sinks/stdout_color_sinks.h"

namespace Engine {
    std::shared_ptr<spdlog::logger> Log::s_Logger;

    void Log::Init() {
        // 格式:[时间] 日志器名称: 消息内容
        spdlog::set_pattern("[%H:%M:%S] %n: %v");
        s_Logger = spdlog::stdout_color_mt("APP");
        s_Logger->set_level(spdlog::level::trace);
    }
}

步骤3:正确调用日志宏

使用{}作为变量占位符,按照spdlog的标准格式化语法调用:

int test_var = 12;
// 用{}绑定变量,实现你想要的输出格式
INFO("The variable is: {}", test_var);
// 若需要在变量后追加字符,直接写在格式化字符串中
INFO("The variable is: {}.", test_var);

执行后即可得到你期望的日志输出:

[23:01:24] APP: The variable is: 12.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:25:22