c++ - Boost.Log 在每个日志语句后刷新

标签 c++ logging boost boost-log

我对 Boost.Log 库有点陌生,第一印象真的很好,但有一件事已经花了很多时间,我无法解决。我想让 Boost.Log 立即将每条消息写入日志文件。我知道其他问题( IIIIII ),但它们没有帮助。考虑这个 example从 boost 文档中,下一个代码是相同的,只是我将 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! 被写入日志文件。

感谢您的帮助!

最佳答案

我做了一些研究。考虑下一个更改的 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,或简单地执行 *.exeDebug 文件夹),当你到达输入部分(std::cin.get())时,只需转到任务管理器并终止进程。根据 auto_flush 的值,接下来的结果是:

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

std::cin.get() 更改为 throw 1 始终给出写入日志文件的前两条记录,关于 if auto_flushReleaseDebug 版本中设置为 truefalse

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

关于c++ - Boost.Log 在每个日志语句后刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218947/

相关文章:

c++ - Win32 从 Window WndProc 获取发送事件的对象的 HWND

c++ - Boost 的链接器错误,在丢弃的部分中引用

ios - 如何为 iPhone (ARM) 构建 boost 1.56.0 boost::context

c++ - 如何生成n位随机数?

c++ - 我可以编写与具有引用参数的 C++ 函数兼容的 C 函数吗?

c++ - `cout << x` 和 `cout.operator <<(x)` 之间的区别?

sql-server - SQL Server 上的命令历史记录

java - 禁用 hibernate 输出

允许 HTML/CSS 输出的 C++ 日志记录库?

c++ - 在同一线程上 boost 互斥锁