到目前为止,我一直在使用
void initLog() {
boost::log::add_common_attributes();
boost::log::add_console_log(std::cout, boost::log::keywords::auto_flush = true,
boost::log::keywords::format = "[%TimeStamp%] [%ThreadID%] [%Severity%] %Message%");
}
int main() {
initLog();
BOOST_LOG_TRIVIAL(info)<<"My message";
}
这产生如下消息[2023-01-31 08:08:13.300149] [0x00007f66a048d000] [info] My message
现在,我想用一个自定义格式化程序来替换这个设置,如下所示:
void coloring_formatter(const boost::log::record_view& record, boost::log::formatting_ostream& stream) {
auto severity = record[boost::log::trivial::severity];
assert(severity);
switch (severity.get()) {
case boost::log::trivial::severity_level::trace:
stream << "\e[97m";
break;
case boost::log::trivial::severity_level::debug:
stream << "\e[34m";
break;
case boost::log::trivial::severity_level::info:
stream << "\e[32m";
break;
case boost::log::trivial::severity_level::warning:
stream << "\e[93m";
break;
case boost::log::trivial::severity_level::error:
stream << "\e[91m";
break;
case boost::log::trivial::severity_level::fatal:
stream << "\e[41m";
break;
}
stream /* << boost::log::extract<boost::posix_time::ptime>("TimeStamp", record) << ": " */ //<< doesnt compile
<< boost::log::extract<unsigned int>("ThreadID", record) << ": " // << empty?
<< record[boost::log::expressions::message]; // << that's the only one working
if (severity) {
stream << "\033[0m";
}
}
void initLogWithFormatter() {
boost::log::add_common_attributes();
auto consoleLog = boost::log::add_console_log(std::cout, boost::log::keywords::auto_flush = true);
consoleLog->set_formatter(&coloring_formatter);
}
int main() {
initLogWithFormatter();
BOOST_LOG_TRIVIAL(info)<<"My message";
}
然而,这并不像我期望的那样访问属性,比如ThreadID,而是简单地输出(至少是彩色的): My message
如何在自定义格式化程序中访问boost::log::record_view&
中boost::log::add_common_attributes()
添加的属性?
1条答案
按热度按时间mklgxw1f1#
我丢失了一个头文件
#include <boost/date_time/posix_time/posix_time_io.hpp>
。现在,格式化程序使用以下实现工作:这将产生与最初配置完全相同的输出-但格式器允许更细粒度的控制(和颜色)。