如何正确日志输出boost::filesystem::path初始化的文件路径?
解决spdlog无法格式化boost::filesystem::path的问题
方案一:直接转换为字符串(快速解决)
boost::filesystem::path自带字符串转换方法,直接转成fmt库支持的类型即可绕过格式化报错:
// 转换为std::string输出 logger::stdout->warn("The outputfilepath looks like {}", outfilepath.string()); // 或者转换为const char*输出(适合路径无特殊字符的场景) logger::stdout->warn("The outputfilepath looks like {}", outfilepath.c_str());
方案二:自定义fmt格式化器(一劳永逸)
如果项目中频繁需要输出boost::filesystem::path,可以给fmt库添加该类型的格式化特化,之后就能直接用路径对象作为spdlog的参数:
- 在全局可见的头文件中添加以下代码:
#include <fmt/format.h> #include <boost/filesystem/path.hpp> namespace fmt { template <> struct formatter<boost::filesystem::path> : formatter<std::string> { template <typename FormatContext> auto format(const boost::filesystem::path& p, FormatContext& ctx) { // 复用std::string的格式化逻辑,将路径转为字符串后输出 return formatter<std::string>::format(p.string(), ctx); } }; }
- 之后即可直接使用原始代码输出路径:
logger::stdout->warn("The outputfilepath looks like {}", outfilepath);
问题原因
spdlog依赖的fmt库默认未提供boost::filesystem::path类型的格式化规则,编译器触发静态断言,要求开发者要么提供该类型的formatter特化,要么将其转换为已支持的类型。
内容的提问来源于stack exchange,提问作者user21641220
相关产品推荐
相关产品推荐

