1. 程式人生 > >boost::log隨筆

boost::log隨筆

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