我对 Boost.Log 库有点陌生,第一印象真的很好,但有一件事已经花了很多时间,我无法解决。我想让 Boost.Log 立即将每条消息写入日志文件。我知道其他问题( I 、 II 、 III ),但它们没有帮助。考虑这个 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,或简单地执行 *.exe
从 Debug
文件夹),当你到达输入部分(std::cin.get()
)时,只需转到任务管理器并终止进程。根据 auto_flush
的值,接下来的结果是:
auto_flush(false)
-- 日志文件为空!auto_flush(true)
-- 日志文件将包含前两条记录,在std::cin.get()
之前生成
将 std::cin.get()
更改为 throw 1
始终给出写入日志文件的前两条记录,关于 if auto_flush
在 Release
和 Debug
版本中设置为 true
或 false
。
因此,结论是 auto_flush
工作正常,只是在直接从 Visual Studio 调试时有一点奇怪的行为。
关于c++ - Boost.Log 在每个日志语句后刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218947/