如何使用自定义 boost::log 格式化程序输出 TimeStamp 和 ThreadID 属性?

How to output TimeStamp and ThreadID attributes with custom boost::log formatter?

我正在使用自定义 boost::log 格式化程序对输出日志消息进行颜色编码,但我找不到添加 TimeStampThreadID属性到日志。当我使用文件记录时,我只是将 keywords::format = "[%TimeStamp%] [%ThreadID%] [%Severity%]: %Message%" 写为 logging::add_file_log 参数。我想在以下自定义格式化程序中产生类似的效果:

void coloring_formatter(const logging::record_view& record,
                        logging::formatting_ostream& stream)
{
  auto severity = record[logging::trivial::severity];
  assert(severity);

  stream << "\e[1m";

  switch (severity.get())
  {
  case logging::trivial::severity_level::trace:
    stream << "\e[97m";
    break;
  case logging::trivial::severity_level::debug:
    stream << "\e[34m";
    break;
  case logging::trivial::severity_level::info:
    stream << "\e[32m";
    break;
  case logging::trivial::severity_level::warning:
    stream << "\e[93m";
    break;
  case logging::trivial::severity_level::error:
    stream << "\e[91m";
    break;
  case logging::trivial::severity_level::fatal:
    stream << "\e[41m";
    break;
  }

  stream // << output TimeStamp
         // << output ThreadID
         << "[" << severity << "] "
         << record[logging::expressions::smessage]
         << "\e[0m";
}

鉴于您已将这些属性添加到日志记录中,有多种方法可以提取它们。最简单的方法是使用 keywords。首先声明属性的关键字:

BOOST_LOG_ATTRIBUTE_KEYWORD(a_timestamp, "TimeStamp", attrs::local_clock::value_type)
BOOST_LOG_ATTRIBUTE_KEYWORD(a_thread_id, "ThreadID", attrs::current_thread_id::value_type)

注意第三个参数是对应属性的值类型。在此示例中,我假设您使用的属性是 local_clock and current_thread_id.

现在您可以使用这些关键字从日志记录中提取值。

stream << record[a_timestamp] << " "
       << record[a_thread_id]
       << " [" << severity << "] "
       << record[logging::expressions::smessage]
       << "\e[0m";