【问题标题】:Boost.Log flush after each logging statementBoost.Log 在每个日志记录语句后刷新
【发布时间】:2013-12-11 16:57:18
【问题描述】:

我对 Boost.Log 库有点陌生,第一印象非常好,但有一件事已经花了很多时间,我无法解决。我想让 Boost.Log 立即将每条消息写入日志文件。我知道其他问题(IIIIII),但它们没有帮助。考虑一下来自 boost docs 的 example,下一个代码是相同的,只是我将 auto_flush 设置为 true

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;
}

调试时,在执行第一个命令(//1)后会创建一个空的sample.log,但是在执行BOOST_LOG后,日志文件仍然是空的,只有在return语句之后,Hello world!才会写入日志文件。

感谢您的帮助!

【问题讨论】:

    标签: c++ logging boost boost-log


    【解决方案1】:

    我做了一些研究。考虑下一个更改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_flushReleaseDebug 构建中是否设置为truefalse

    所以,结论是 auto_flush 工作正常,只是在直接从 Visual Studio 调试时有点奇怪。

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2018-11-08
      • 2015-06-26
      • 1970-01-01
      相关资源
      最近更新 更多