I'm a bit new to Boost.Log library, first impressions are really good, but one thing is already took a lot of hours and I can't solve it. I want to make Boost.Log to write each message to a log file immediately. I'm aware of other questions (I, II, III), however they didn't help. Consider this example from boost docs, the next code is the same except that I've set auto_flush to 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;
}

While debugging, an empty sample.log is created after execution of first command (//1), however after executing BOOST_LOG, log file remains empty, only after return statement, Hello world! is written to log file.

Thanks for help!

有帮助吗?

解决方案

I did some research. Consider next changed main function:

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

So std::cin.get() acts as pause, launch application in normal mode (without debugging, Ctrl + F5 from VS2008, or simply executing *.exefrom Debug folder) and when you reach input part (std::cin.get()) just go to Task Manager and kill the process. Depending on value of auto_flush results are next:

  • auto_flush(false) -- log file is empty!
  • auto_flush(true) -- log file will contain first two records, made before std::cin.get()

Changing std::cin.get() to throw 1 gives always first two records being written to log file, regarding of if auto_flush set to true or false both in Release and Debug builds.

So, the conclusion is that auto_flush works fine, it's just has a bit strange behaviour when debugging directly from Visual Studio.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top