Optimizations:
In this example, all output will be written to the console, debug window, and "out.txt" file. It will look similar to:
00001 [T5884] [1] message 0 00002 [T7168] [2] message 0 00003 [T7932] [3] message 0 00004 [T740] [4] message 0 00005 [T8124] [5] message 0 00006 [T5884] [6] message 1 00007 [T5884] [7] message 2 00008 [T740] [8] message 1 00009 [T7168] [9] message 1 00010 [T7932] [10] message 1 00011 [T8124] [11] message 1 00012 [T5884] [12] message 3 00013 [T7168] [13] message 2 00014 [T5884] [14] message 4 00015 [T740] [15] message 2 00016 [T7932] [16] message 2 00017 [T8124] [17] message 2 00018 [T7168] [18] message 3 00019 [T5884] [19] message 5 00020 ...
00001 00050 #include <boost/logging/format_fwd.hpp> 00051 BOOST_LOG_FORMAT_MSG( optimize::cache_string_one_str<> ) 00052 00053 #include <boost/logging/format_ts.hpp> 00054 #include <boost/logging/format/formatter/thread_id.hpp> 00055 #include <boost/thread/thread.hpp> 00056 #include <boost/thread/xtime.hpp> 00057 00058 using namespace boost::logging; 00059 00060 typedef logger_format_write< default_, default_, writer::threading::ts_write > logger_type; 00061 00062 #define L_ BOOST_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() ) 00063 00064 BOOST_DEFINE_LOG_FILTER(g_log_filter, filter::no_ts ) 00065 BOOST_DEFINE_LOG(g_l, logger_type) 00066 00067 void do_sleep(int ms) { 00068 using namespace boost; 00069 xtime next; 00070 xtime_get( &next, TIME_UTC); 00071 next.nsec += (ms % 1000) * 1000000; 00072 00073 int nano_per_sec = 1000000000; 00074 next.sec += next.nsec / nano_per_sec; 00075 next.sec += ms / 1000; 00076 next.nsec %= nano_per_sec; 00077 thread::sleep( next); 00078 } 00079 00080 void use_log_thread() { 00081 for ( int i = 0; i < 50; ++i) { 00082 L_ << "message " << i ; 00083 do_sleep(1); 00084 } 00085 } 00086 00087 void ts_logger_one_filter_example() { 00088 // add formatters and destinations 00089 // That is, how the message is to be formatted and where should it be written to 00090 g_l()->writer().add_formatter( formatter::idx(), "[%] " ); 00091 g_l()->writer().add_formatter( formatter::thread_id(), "[T%] " ); 00092 g_l()->writer().add_formatter( formatter::append_newline() ); 00093 g_l()->writer().add_destination( destination::file("out.txt") ); 00094 g_l()->writer().add_destination( destination::cout() ); 00095 g_l()->writer().add_destination( destination::dbg_window() ); 00096 g_l()->mark_as_initialized(); 00097 00098 for ( int i = 0 ; i < 5; ++i) 00099 boost::thread t( &use_log_thread); 00100 00101 // allow for all threads to finish 00102 do_sleep( 5000); 00103 } 00104 00105 00106 00107 00108 int main() { 00109 ts_logger_one_filter_example(); 00110 } 00111 00112 00113 // End of file 00114