我正在使用组合的严重性和通道记录器来获取日志记录输出的某种范围。
问题是我想为整个项目使用单个日志记录对象,因此希望能够为特定记录设置通道,并且我无法同时设置严重性和通道。我可以设置或者,但不能同时设置两者。
示例代码:
#include <iostream>
#include <boost/log/trivial.hpp>
#include <boost/log/sources/severity_channel_logger.hpp>
#include <boost/log/utility/manipulators/add_value.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/core/null_deleter.hpp>
namespace logging = boost::log;
using logger_type = logging::sources::severity_channel_logger_mt<logging::trivial::severity_level>;
int main()
{
logging::add_common_attributes();
using text_sink_type = logging::sinks::synchronous_sink<logging::sinks::text_ostream_backend>;
auto sink = boost::make_shared<text_sink_type>();
sink->locked_backend()->add_stream(boost::shared_ptr<std::ostream>(&std::clog, boost::null_deleter()));
sink->set_formatter(
logging::expressions::stream
<< logging::expressions::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << " :: "
<< '[' << logging::trivial::severity << " - " << logging::expressions::attr<std::string>("Channel") << "] "
<< logging::expressions::smessage
);
logging::core::get()->add_sink(sink);
logger_type logger;
auto rec = logger.open_record(logging::keywords::severity = logging::trivial::info);
if (rec)
{
// This do not work
rec.attribute_values()["Channel"] = logging::attributes::make_attribute_value(std::string{"bar"});
logging::record_ostream ros{rec};
// This do not work either
ros << logging::add_value("Channel", std::string{"foo"});
ros << "Some message";
ros.flush();
logger.push_record(std::move(rec));
}
}
上面的代码将输出
2016-09-27 10:25:38.941645 :: [info - ] Some message
如图所示,频道名称不在输出中。
打开记录时我可以轻松设置频道名称:
auto rec = logger.open_record(logging::keywords::channel = std::string{"channel"});
但是我无法设置正确的严重程度。
有没有办法为单个记录设置严重性和频道?或者我是否必须使用多个记录器对象,每个通道一个?
除此之外,我可以轻松地为每个输出创建新的日志记录对象,但即使是少量日志记录也是如此。
答案 0 :(得分:1)
open_record()
采用一组属性。后者是通过重载的逗号运算符构建的。但是,为了将逗号的解释抑制为函数参数分隔符,必须添加一对额外的括号。
auto rec = logger.open_record( (logging::keywords::channel = std::string{"channel"}, logging::keywords::severity = logging::trivial::info) );