使用 {fmt} & source_location 创建基于可变模板的日志记录函数

7
我想在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: error: missing default argument on parameter 'args'

是否可能将可变参数模板和参数的默认值混合使用?如果可以,应该如何操作?

此外,是否有一种方法可以将"{},{}, "部分附加到编译时的format字符串前面,以产生另一个编译时字符串(用作格式)?

1个回答

18

您可以使用表示格式字符串和位置的结构体来完成此操作:

#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


但是如果你使用 log(FMT_STRING("invalid squishiness: {} {}"), 42);,它将不会产生编译时错误。 - Alexander Chen
FMT_STRING是一个遗留的API,当尝试传递给日志函数时,它不会编译:https://godbolt.org/z/z3zjxhYTP - vitaut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接