使用 {fmt} 和 source_location 创建基于可变参数模板的日志功能

问题描述

我想在 C++ 中创建一个简单的日志函数,它将代码位置添加到日志消息中。我想避免使用宏以及 __FILE____LINE__ 的使用。

请注意,format 字符串始终是编译时字符串,我希望在编译时进行尽可能多的计算(目标机器是一个小型 MCU)。

我可以通过 experimental/source_location 使用 C++20 source_location 功能。 我也可以使用 {fmt}

我从 this 开始。目前,我有以下几点:

#include <fmt/format.h>
#include <experimental/source_location>

using source_location = std::experimental::source_location;

void vlog(fmt::string_view format,fmt::format_args args)
{
  fmt::vprint(format,args);
}

template <typename S,typename... Args>
void log(const S& format,const source_location& location,Args&&... args)
{
  vlog(format,fmt::make_args_checked<fmt::string_view,uint32_t,Args...>(format,location.file_name(),location.line(),args...));
}

#define MY_LOG(format,...) log(FMT_STRING("{},{}," format),source_location::current(),__VA_ARGS__)

int main() {
  MY_LOG("invalid squishiness: {}",42);
}

正确产生./example.cpp,20,invalid squishiness: 42

在我看来,我很接近。我认为剩下的就是让 log 函数采用 source_location认参数(我知道将 source_location::current() 作为认参数是一种很好的做法)。但我收到以下错误

:12:99: 错误:缺少参数“args”的认参数

这甚至可以混合可变参数模板和参数的认参数吗?如果是这样,如何?

另外,有没有办法将 "{}," 部分添加到编译时 format 字符串以产生另一个编译时字符串(用作格式)?

解决方法

您可以使用表示格式字符串和位置的结构来实现:

#include <fmt/core.h>
#include <source_location>

struct format_string {
  fmt::string_view str;
  std::source_location loc;

  format_string(
      const char* str,const std::source_location& loc =
        std::source_location::current()) : str(str),loc(loc) {}
};

void vlog(const format_string& format,fmt::format_args args) {
  const auto& loc = format.loc;
  fmt::print("{}:{}: ",loc.file_name(),loc.line());
  fmt::vprint(format.str,args);
}

template <typename... Args>
void log(const format_string& format,Args&&... args) {
  vlog(format,fmt::make_format_args(args...));
}

int main() {
  log("invalid squishiness: {}",42);
}

打印:

./example.cpp:26: invalid squishiness: 42

Godbolt:https://godbolt.org/z/4aMKcW