【问题标题】:How to print to different logs with different attributes by boost::log?如何通过 boost::log 打印到具有不同属性的不同日志?
【发布时间】:2016-12-02 18:50:14
【问题描述】:

例如,我的日志消息有 4 个级别(或属性):

"error","warning","exception","action".

我想将属性为“error”或“exception”的消息打印到fatal.log,并将属性为“action”和“warning”的消息打印到regular.log。 通过在线搜索:

boost::shared_ptr<sinks::text_multifile_backend> backend = boost::make_shared< sinks::text_multifile_backend >();
backend->set_file_name_composer
(
    sinks::file::as_file_name_composer(boost::log::expressions::stream <<  boost::log::expressions::attr< std::string >("level") << ".log")
);

typedef sinks::synchronous_sink< sinks::text_multifile_backend > sink_t;
boost::shared_ptr< sink_t > sink(new sink_t(backend));

// Set the formatter
sink->set_formatter
    (
    boost::log::expressions::stream
    << boost::log::expressions::attr< std::string >("level")
    << boost::log::expressions::smessage
    );

看来我可以按级别(属性)生成不同的日志文件并使用

BOOST_LOG_SEV(_logger, level) << message;

将不同的消息打印到不同的日志。但这似乎会生成 4 个日志,而不仅仅是 2 个日志,因为我有 4 个级别(属性)。如何将带有属性的消息打印到一个日志中,将带有其他属性的消息打印到另一个日志中?

【问题讨论】:

  • 你可能可以通过在你的文件接收器上设置过滤器来解决这个问题,一个是过滤属性等于“错误”或“异常”,另一个是“操作”和“警告”

标签: c++ logging boost


【解决方案1】:

从boost documentation 借用一些代码,您可能可以摆脱这种方法:

    using text_sink = sinks::synchronous_sink< sinks::text_ostream_backend >;
    boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();

    sink->locked_backend()->add_stream(
        boost::make_shared< std::ofstream >("regular.log"));

    // set your 1st formatter

    sink->set_filter(expr::has_attr(tag_attr) && (tag_attr == "action" || tag_attr == "warning"));

    logging::core::get()->add_sink(sink);

    sink = boost::make_shared< text_sink >();

    sink->locked_backend()->add_stream(
        boost::make_shared< std::ofstream >("fatal.log"));

    // set your 2nd formatter

    sink->set_filter(expr::has_attr(tag_attr) && (tag_attr == "error" || tag_attr == "exception"));

    logging::core::get()->add_sink(sink);

【讨论】:

  • 它显示没有合适的用户定义转换从 boost::make_shared<:ofstream> 到 const boost::make_shared<:basic_stream>”。顺便说一下,如果我想根据日期生成文件名,我可以使用 sink->locked_backend()->add_stream( boost::make_shared("Regular_%Y-%m-%d_%H- %M-%S.log""));?
  • 能否请您指定它在哪一行失败?至于另一个问题,我建议阅读文档
  • 在 sink->locked_backend()->add_stream( boost::make_shared("regular.log")) 失败;
  • 我一直在寻找 logging::core 的头文件,但我找不到。 VS2013 一直说找不到 logging::core。你能告诉我吗?
  • 这个头文件我已经试过了,但是对我不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 2023-02-10
  • 2020-05-05
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多