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

时间:2016-07-27 16:04:21

标签: c++ logging boost boost-log boost-logging

我使用自定义boost::log格式化程序对输出日志消息进行颜色编码,但我未能找到添加 TimeStamp 的正确方法ThreadID 属性到日志。当我使用文件记录时,我只需将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";
}

1 个答案:

答案 0 :(得分:4)

鉴于您已将这些属性添加到日志记录中,有多种方法可以提取它们。最简单的方法是使用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_clockcurrent_thread_id

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

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