2013-11-26 109 views
4

我對Boost.Log庫有點新,第一印象真的很好,但有一件事情已經花了很多小時,我無法解決它。我想讓Boost.Log立即將每條消息寫入日誌文件。我知道其他問題(IIIIII),但他們沒有幫助。考慮這個example從升壓文檔,下一個代碼是不同的,我已經設置相同auto_flushtrueBoost.Log刷新後每個日誌語句

namespace logging = boost::log; 
namespace src = boost::log::sources; 
namespace sinks = boost::log::sinks; 

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")); //1 

    sink->locked_backend()->auto_flush(true); 

    // Register the sink in the logging core 
    logging::core::get()->add_sink(sink); 
} 

int main(int, char*[]) 
{ 
    init(); 

    src::logger lg; 
    BOOST_LOG(lg) << "Hello world!"; 

    return 0; 
} 

調試時,一個空sample.log是第一個命令(// 1)執行後創建的,但執行BOOST_LOG後,只有在return語句,Hello world!寫入日誌文件之後,日誌文件纔會保持爲空。

感謝您的幫助!

回答

5

我做了一些研究。接下來考慮改變main功能:在正常模式下

int main(int, char*[]) 
{ 
    init(); 

    src::logger lg; 
    BOOST_LOG(lg) << "Hello world #1!"; 
    BOOST_LOG(lg) << "Hello world #2!"; 
    std::cin.get(); 
    BOOST_LOG(lg) << "Hello world #3!"; 
    BOOST_LOG(lg) << "Hello world #4!"; 

    return 0; 
} 

所以std::cin.get()充當暫停,啓動應用程序(從VS2008無需調試,按Ctrl + F5,或簡單地從Debug文件夾執行*.exe),當你到達輸入部分(std::cin.get() )只要去任務管理器並殺死進程。根據auto_flush的值,結果是:

  • auto_flush(false) - 日誌文件爲空!
  • auto_flush(true) - 日誌文件將包含前兩項紀錄,取得std::cin.get()

更改std::cin.get()throw 1給人總是被寫入前兩條記錄到日誌文件,關於是否auto_flush設置爲truefalse無論在Release之前和Debug構建。

所以,結論是auto_flush工作正常,直接從Visual Studio中調試時,它有點奇怪的行爲。