我在整个项目中使用多个具有不同“ channel ”属性的 severity_channel_logger_mt
实例。但是,对于一个特定的日志行,我想直接在调用中设置“Channel”属性。使用宏 BOOST_LOG_CHANNEL_SEV(logger, channel, severity)
,这其实并不难做到。但是,这会更改“Channel”属性。后续的日志记录调用将不会使用初始 channel 属性,而是使用上次日志记录调用后更改的 channel 属性。
我发现将 channel 属性更改回原始值的唯一方法是:误用记录器对象的 open_record()
函数。
我的问题:有更优雅的方法吗?是否有允许直接设置记录器属性的特定函数?
突出显示过程的代码片段:
auto & lg = global_logger::get();
BOOST_LOG_CHANNEL_SEV(lg, "test-subsystem", exec_severity) << "Message 1";
// misuse the open_record call to set the channel attribute
// reset channel name back to "global"
auto rc = lg.open_record(boost::log::keywords::channel = "global" );
rc.reset(); // attempt to clean-up a bit
BOOST_LOG_CHANNEL(lg, exec_severity) << "Message 2";
在上面的示例中,“消息 1”应来自“测试子系统”,但其他消息应来自“全局” channel 。如果 open_record()
和 rc.reset();
行被注释掉,则两条消息都来自“测试系统”
更新:
我最终实现了一个稍微不同的解决方案
- 我为这些日志消息创建了一个专用的记录器
- 我使用
BOOST_LOG_CHANNEL_SEV()
记录到这个记录器,它接受一个参数来在每次调用时设置“ channel ”名称
上面更新后的代码片段如下所示:
auto & stlog = global_logger::get();
auto & lg = special_logger::get();
BOOST_LOG_CHANNEL_SEV(lg, "test-subsystem", exec_severity) << "Message 1";
// this log line will be in channel "global" again
BOOST_LOG_SEV(stlog, exec_severity) << "Message 2";
最佳答案
is there a more elegant way of doing this?
正如您在 channel 专题中看到的那样 reference部分,有一个channel
方法,可以用来设置 channel 名称。该方法被logger继承。
但是,出于性能原因,通常建议避免修改 channel 名称。当您有多个具有相应 channel 名称的不同子系统时,最好为每个子系统专用一个单独的记录器。否则,您需要为在每个日志记录上设置 channel 名称以及必要的线程同步支付性能开销。
关于c++ - boost::log 在 channel 记录器中设置 "Channel"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038890/