boost::log包含兩個大部分:logger和sink
logging::core是全局的一個單例
1,sink
在boost::log中有一個默認的sink與控制台流相關關聯;
如果想把日志輸出到指定的文件流中可以使用如下代碼:
auto sink=add_log_file("xxx.log");
上面的一行代碼與下面是等價的:
===========================================================================
void init()
{
// Construct the sink
typedef sinks::synchronous_sink< sinks::text_ostream_backend > text_sink;
boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();
// Add a stream to write log to
sink->locked_backend()->add_stream(
boost::make_shared< std::ofstream >("sample.log"));
// Register the sink in the logging core
logging::core::get()->add_sink(sink);
}
===========================================================================
從上面的代碼中可能知道add_log_file內部是把相關的sink已經加入到loggint::core了;
如果要使用多個sink,可以通過設置channel屬性,eg
1 typedef boost::log::sources::channel_logger_mt<> channel_logger; 2 3 std::shard_ptr<channel_logger> create_logger(const std::string& channel) 4 { 5 auto sink = add_file_log( 6 keywords::file_name="xx.log", 7 keywords::channel=channel 8 ); 9 10 //只將屬於此channel的信息輸出到xx.log 11 sink->set_filter(expr::attr<std::string>("Channel")==channel); 12 13 return std::shared_ptr<channel_logger>(new channel_logger(keywords::channel)); 14 }
如此就創建一個指向channel相關的logger,有了logger就可以打印日志了,eg
std::shared<channel_logger> logger = create_logger("my_channel");
BOOST_LOG(*logger)<<"Hello World!";
這樣就可以在xx.log文件中看到Hello World!信息了
參考鏈接:http://www.wanguanglu.com/2016/07/28/boost-log-document/#detailed-logging-source
https://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/log/detailed/sources.html