如何在配置文件中配置 Boost 日志过滤器

How to config Boost logging filter in configuration file

我在 Windows 10 上使用 VS2015 中的 Boost 1.63。

代码如下Boost example.

这是代码,似乎 'severityLogger.open_record' 生成的记录无效,它没有进入 if 语句。

#include <boost/format.hpp>
#include <boost/locale/generator.hpp>
#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/from_settings.hpp>
#include <boost/log/utility/setup/settings_parser.hpp>
#include <boost/phoenix.hpp>

namespace logging = boost::log;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;
namespace sinks = boost::log::sinks;
namespace src = boost::log::sources;

src::wseverity_logger<logging::trivial::severity_level> severityLogger;
std::wifstream strm(L"config\logger.ini");
strm.imbue(std::locale(strm.getloc(), new std::codecvt_utf8<wchar_t, 0x10ffff, std::consume_header>));
auto settings = logging::parse_settings(strm);
logging::init_from_settings(settings);
logging::add_common_attributes();

auto rec = severityLogger.open_record(keywords::severity = logging::trivial::severity_level::info);
if (rec) { // Unable to go here !!!
    logging::wrecord_ostream strm(rec);
    strm << L"Some message";
    strm.flush();
    severityLogger_.push_record(boost::move(rec));
}

但是,如果我添加这段代码就可以正常工作:

logging::core::get()->set_filter(
    logging::trivial::severity >= logging::trivial::info);

这是我的配置文件:

[Core]
DisableLogging=false
Filter="%Severity% >= info"

[Sinks.File]
Destination=TextFile
FileName="App_%Y-%m-%d.%N.log"
Format="%TimeStamp% %Severity% - %Message%"
AutoFlush=true
TimeBasedRotation="00:00:00"
RotationSize=10485760

问题是默认情况下过滤器解析器不期望 logging::trivial::severity_level 类型的属性。因此,已解析的过滤器无法识别严重级别并拒绝日志记录。

您需要按照 this section. Basically, this needs to be done for any attributes that have value types other than those mentioned in this 部分所述,通过注册过滤器工厂来指示属性值类型。建议注册所有属性,即使是那些列出的属性,因为否则库在处理过滤器时必须对默认支持的所有类型执行更昂贵的查找。

您可能还需要注册一个格式化程序工厂,类似于过滤器工厂。