Boost.log:使用C++11 lambda表达式过滤严重性级别

3

我正在使用Boost.Log实现日志记录器。我有一个全局日志记录器,其中包含一个输出到控制台的sink,并且如果调用init方法,则可选地输出到文件。

我想使用C++11 lambda表达式来设置严重性过滤器。从文档中看,这是可能的:http://www.boost.org/doc/libs/1_59_0/libs/log/doc/html/log/tutorial/trivial_filtering.html

然而,我没有找到任何示例,而我的朴素尝试也不能编译。

我的init函数如下:

template <typename filter_type>
void init_log_file( filter_type filter)
{
    boost::shared_ptr< boost::log::sinks::text_file_backend > backend =
        boost::make_shared< boost::log::sinks::text_file_backend >
            (
            boost::log::keywords::file_name = "log_%Y-%m-%d_%H-%M-%S.%N.log", 
            boost::log::keywords::rotation_size = 10 * 1024 * 1024,
            boost::log::keywords::max_size = 1000 * 1024 * 1024,
            boost::log::keywords::min_free_space = 2000 * 1024 * 1024,
            boost::log::keywords::auto_flush = true
        );
typedef boost::log::sinks::synchronous_sink< boost::log::sinks::text_file_backend > sink_t;
boost::shared_ptr< sink_t > sink(new sink_t(backend));

    sink->set_filter( filter(severity) );
    //sink->set_filter( filter(severity.or_none(), tag_attr.or_none()) );
    boost::log::core::get()->add_sink(sink);
}

我将init函数如下调用:

int main() 
{
    //typedef boost::log::value_ref< custom_severity_level, tag::severity > sev_type;
    typedef boost::log::expressions::attribute_keyword<tag::severity> sev_type;
   init_log_file([](sev_type const& level)
   {
       return level == custom_severity_level::ERROR;
   });

   return 0;
}

我尝试了几个方法,但是要么lambda参数类型不匹配,要么会出现错误:

错误:未定义模板的隐式实例化'boost::log::v2_mt_posix::expressions::aux::date_time_formatter_generator_traits' m_name(name), m_formatter(formatter_generator::parse(format)), m_visitor_invoker(fallback)

有没有提示如何正确实现我的想法的任何提示都将非常棒。

提前感谢您的回复

编辑:Kassiar的答案解决了我的问题。

1个回答

3
我发现以下签名的函数适合于set_filter方法的要求:
bool(const boost::log::attribute_value_set&)

使用这个签名,可以实现使用过滤器的Trivial logging with filters example。Boost.Log tutorial可以按照以下方式进行实现:
#include <boost/log/trivial.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>

namespace logging = boost::log;
namespace sinks = boost::log::sinks;

void init_logging()
{
    logging::core::get()->set_filter([](const logging::attribute_value_set& attr_set)
    {
        return attr_set["Severity"].extract<logging::trivial::severity_level>() >= logging::trivial::info;
    });
}

int main(int argc, char** argv)
{
    init_logging();

    BOOST_LOG_TRIVIAL(trace) << "Trace level log message";
    BOOST_LOG_TRIVIAL(debug) << "Debug level log message";
    BOOST_LOG_TRIVIAL(info) << "Info level log message";
    BOOST_LOG_TRIVIAL(warning) << "Warning level log message";
    BOOST_LOG_TRIVIAL(fatal) << "Fatal level log message";
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接