2013-12-23 57 views
1

下面是我的完整測試代碼,我打印當前的線程ID,但它看起來很長,是否正確?因爲我使用BOOST_LOG_SCOPED_THREAD_TAG,我可以在其他線程中記錄線程ID嗎?不確定我在boost日誌中的線程ID是否正確?

#include <fstream> 
#include <boost/shared_ptr.hpp> 
#include <boost/make_shared.hpp> 
#include <boost/log/core.hpp> 
#include <boost/log/trivial.hpp> 
#include <boost/log/expressions.hpp> 
#include <boost/log/sinks/sync_frontend.hpp> 
#include <boost/log/sinks/text_ostream_backend.hpp> 
#include <boost/log/sources/severity_logger.hpp> 
#include <boost/log/sources/record_ostream.hpp> 
#include <boost/log/utility/setup/common_attributes.hpp> 
#include <boost/log/support/date_time.hpp> 
#include <boost/thread/thread.hpp> 
#include <boost/log/attributes/scoped_attribute.hpp> 
namespace logging = boost::log; 
namespace src = boost::log::sources; 
namespace expr = boost::log::expressions; 
namespace sinks = boost::log::sinks; 
namespace keywords = boost::log::keywords; 
void InitLog() { 
    typedef sinks::synchronous_sink<sinks::text_ostream_backend> text_sink; 
    boost::shared_ptr<text_sink> sink = boost::make_shared<text_sink>(); 
    sink->locked_backend()->add_stream(
        boost::make_shared<std::ofstream>("sign.log")); 
    sink->locked_backend()->add_stream(
        boost::make_shared<std::ofstream>("csv.log")); 

    sink->set_formatter (
       expr::format("[%1%]<%2%>(%3%): %4%") 
       % expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S") 
       % logging::trivial::severity 
       % expr::attr<boost::log::attributes::current_thread_id::value_type >("ThreadID") 
       % expr::smessage 
       ); 
    logging::core::get()->add_sink(sink); 
    logging::add_common_attributes(); 
    BOOST_LOG_SCOPED_THREAD_TAG("ThreadID", boost::this_thread::get_id()); 
} 
int main(int, char*[]) { 
    InitLog(); 
    using namespace logging::trivial; 
    src::severity_logger<severity_level> lg; 
    BOOST_LOG_SEV(lg, trace) << "A trace severity message"; 
    BOOST_LOG_SEV(lg, debug) << "A debug severity message"; 
    BOOST_LOG_SEV(lg, info) << "An informational severity message"; 
    BOOST_LOG_SEV(lg, warning) << "A warning severity message"; 
    BOOST_LOG_SEV(lg, error) << "An error severity message"; 
    BOOST_LOG_SEV(lg, fatal) << "A fatal severity message"; 
    return 0; 
} 

測試程序生成兩個日誌文件:sign.log和csv.log,他們有相同的內容,像這樣:

[2013-12-23 23:38:47]<trace>(0x00007f1f8a173740): A trace severity message 
[2013-12-23 23:38:47]<debug>(0x00007f1f8a173740): A debug severity message 
[2013-12-23 23:38:47]<info>(0x00007f1f8a173740): An informational severity message 
[2013-12-23 23:38:47]<warning>(0x00007f1f8a173740): A warning severity message 
[2013-12-23 23:38:47]<error>(0x00007f1f8a173740): An error severity message 
[2013-12-23 23:38:47]<fatal>(0x00007f1f8a173740): A fatal severity message 

回答