每个日志记录语句后Boost.Log刷新

时间:2013-11-26 13:52:33

标签: c++ logging boost boost-log

我对Boost.Log库有点新鲜,第一印象非常好,但有一件事已经花费了很多时间而我无法解决。我想让Boost.Log立即将每条消息写入日志文件。我知道其他问题(IIIIII),但他们没有帮助。考虑来自提升文档的这个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!被写入日志文件。

感谢您的帮助!

1 个答案:

答案 0 :(得分: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,或只是从*.exe文件夹执行Debug)以及当您到达输入部分时(std::cin.get())只需转到任务管理器并终止该过程。取决于auto_flush的值,接下来是:

  • auto_flush(false) - 日志文件为空!
  • auto_flush(true) - 日志文件将包含在std::cin.get()
  • 之前创建的前两条记录

std::cin.get()更改为throw 1始终会将前两条记录写入日志文件,关于auto_flush是否设置为truefalse { {1}}和Release版本。

因此,结论是Debug工作正常,直接从Visual Studio调试时,它只是有点奇怪的行为。