我正在使用组合的严重性和 channel 记录器来获取日志输出的某种范围。
问题是我想为整个项目使用单个日志记录对象,因此希望能够为特定记录设置 channel ,但我无法同时设置严重性和 channel 。我可以设置其中一个或,但不能同时设置两者。
示例代码:
#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
As seen, the channel name is not in the output.
I can easily set the channel name when opening the record:
auto rec = logger.open_record(logging::keywords::channel = std::string{"channel"});
但是我无法设置正确的严重性。
有没有办法为单个记录设置严重性和 channel ?或者我是否必须使用多个记录器对象,每个 channel 一个?
我可以轻松地为每个输出创建新的日志记录对象,但即使对于少量的日志记录,这也似乎过多。
最佳答案
open_record()
采用一组属性。后者是通过重载的逗号运算符构建的。但是,为了禁止将逗号解释为函数参数分隔符,您必须添加一对额外的括号。
auto rec = logger.open_record( (logging::keywords::channel = std::string{"channel"}, logging::keywords::severity = logging::trivial::info) );
关于c++ - 为每条记录设置严重性和 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39719878/