boost库编译完成后,运行官方的例子,编译时因没有提示容易出错,现把容易出错的点记录一下
#include <boost/log/core.hpp> 2 #include <boost/log/trivial.hpp> 3 #include <boost/log/expressions.hpp> 4 #include <boost/log/sinks/text_file_backend.hpp> 5 #include <boost/log/utility/setup/file.hpp> 6 #include <boost/log/utility/setup/common_attributes.hpp> 7 #include <boost/log/sources/severity_logger.hpp> 8 #include <boost/log/sources/record_ostream.hpp> 9 #include <boost/log/support/date_time.hpp> 10 11 namespace logging = boost::log; 12 namespace src = boost::log::sources; 13 namespace sinks = boost::log::sinks; 14 namespace keywords = boost::log::keywords; 15 #if 0 16 void init() 17 { 18 logging::add_file_log 19 ( 20 keywords::file_name = "sample_%N.log", 21 keywords::rotation_size = 10 * 1024 * 1024, 22 keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), 23 keywords::format = "[%TimeStamp%]: %Message%" 24 ); 25 26 logging::core::get()->set_filter 27 ( 28 logging::trivial::severity >= logging::trivial::info 29 ); 30 } 31 #else 32 void init() 33 { 34 logging::add_file_log 35 ( 36 keywords::file_name = "sample_%T.log", /*< file name pattern >*/ 37 keywords::rotation_size = 10 * 1024 * 1024, /*< rotate files every 10 MiB... >*/ 38 keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), /*< ...or at midnight >*/ 39 keywords::format = "[%TimeStamp%]: %Message%" /*< log record format >*/ 40 ); 41 42 logging::core::get()->set_filter 43 ( 44 logging::trivial::severity >= logging::trivial::info 45 ); 46 } 47 #endif 48 int main(int, char*[]) 49 { 50 init(); 51 logging::add_common_attributes(); 52 53 using namespace logging::trivial; 54 src::severity_logger< severity_level > lg; 55 56 BOOST_LOG_SEV(lg, trace) << "A trace severity message"; 57 BOOST_LOG_SEV(lg, debug) << "A debug severity message"; 58 BOOST_LOG_SEV(lg, info) << "An informational severity message"; 59 BOOST_LOG_SEV(lg, warning) << "A warning severity message"; 60 BOOST_LOG_SEV(lg, error) << "An error severity message"; 61 BOOST_LOG_SEV(lg, fatal) << "A fatal severity message"; 62 63 return 0; 64 }
如上代码编译时容易出错,需要注意的点如下:
1.编译时需要指定编译的宏-DBOOST_ALL_DYN_LINK,或者在源文件中定义宏 #define BOOST_ALL_DYN_LINK也行;
2.编译时需要同时链接-lboost_log_setup,-lboost_log两个动态库文件;
3.编译需指定相应的相应库所在文件,-L +filkpath
完整正确的编译命令如下:
g++ -o test_log src(cpp) -I headfilepath -L libfilepath -lboost_log -lboost_log_setup -lboost_thread -lpthread -DBOOST_ALL_DYN_LINK