c++ - boost::log 在 channel 记录器中设置 "Channel"属性

标签 c++ c++11 visual-studio-2015 boost-log

我在整个项目中使用多个具有不同“ 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/

相关文章:

c++ - 带有内存定位文件的 FFmpeg avformat_open_input

c++ - 如果内存池比malloc快,为什么malloc不能在幕后使用它们?

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++11 - 如何在 CMake 中激活 C++ 11?

c++ - Multimap 使用 std::make_pair 与 std::pair 构造函数插入键类型信息

c++传递数组而不是可变长度参数列表

c++ - 带两个参数的 decltype 是什么?

c# - 彩色启动画面 - UWP 应用程序

git - 每个 Visual Studio 版本都需要自己克隆的 git 存储库吗?

c# - 如何将视觉冲突解决(P4Merge)集成到SourceTree中