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

孤街醉人 提交于 2019-12-23 20:35:30

问题


I'm using custom boost::log formatter for color coding the output log message, but I'm failing to find the proper way to add TimeStamp and ThreadID attributes to the log. When I'm using file logging I just write keywords::format = "[%TimeStamp%] [%ThreadID%] [%Severity%]: %Message%" as logging::add_file_log parameter. I want to have similar effect in the following custom formatter:

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:


Given that you have added these attributes to log records, there are multiple ways to extract them. The simplest way is to use keywords. First you declare keywords for the attributes:

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)

Note that the third parameter is the value type of the corresponding attribute. In this example I assumed that the attributes you used were local_clock and current_thread_id.

Now you can use these keywords to extract the value from log records.

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


来源:https://stackoverflow.com/questions/38618094/how-to-output-timestamp-and-threadid-attributes-with-custom-boostlog-formatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!