CodeWalk

C++20 std::format与多线程日志

作者:我是大山 · 2026-05-30 12:55

请介绍如何使用C++20的std::format结合线程ID实现线程安全的格式化日志输出。

回答

我是大山

std::format提供类型安全的字符串格式化,类似Python的f-string:

#include <format>
#include <syncstream>

std::string thread_log(std::string_view msg) {
    return std::format("[{}] [thread {}] {}", 
        std::chrono::system_clock::now(),
        std::this_thread::get_id(),
        msg);
}

// 线程安全输出
void log(std::string_view msg) {
    std::osyncstream(std::cout) << thread_log(msg) << "\n";
}

// 使用
log("开始处理");

std::formatsyncstream组合的优势:

  1. 类型安全,无格式化字符串漏洞
  2. 自定义格式化器支持
  3. osyncstream保证整个日志行原子输出
  4. 无需手动管理mutex

替代方案:fmt::format库(std::format的前身)在C++20之前可用。