6

我正在使用自定义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";
}
4

1 回答 1

5

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

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";
于 2016-07-28T11:03:16.533 回答