Search code examples
c++boost

boost log - handling power off scenario


I have implemented a global logger using boost 1.63. Here is initialization:

BOOST_LOG_GLOBAL_LOGGER_INIT(my_logger, src::severity_logger_mt< severity_level >)
{
    typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink;
    boost::shared_ptr< file_sink > sink(new file_sink(
    keywords::file_name = "/var/log/testApp/%Y%m%d_%H%M%S_testApp.log",
    keywords::rotation_size = 5 * 1024 * 1024,
    keywords::auto_flush = true));

    sink->locked_backend()->set_file_collector(sinks::file::make_collector(
    keywords::target = "/var/log/testApp/oldLogs",
    keywords::max_size = 5 * 1024 * 1024 * 2,
    keywords::min_free_space = 5 * 1024 * 1024 * 2,
    keywords::max_files = 2));

    sink->locked_backend()->scan_for_files();

    sink->set_formatter(
    expr::format("[%1%]<%2%> : %3%") %
    expr::attr< boost::posix_time::ptime >("TimeStamp") %
    expr::attr< severity_level >("Severity") %
    expr::smessage);

    logging::core::get()->add_sink(sink);
    logging::core::get()->add_global_attribute("TimeStamp", attrs::local_clock());

    src::severity_logger_mt< severity_level > slg;
    return slg;
}

When a program is unexpectedly finished (for example sudo kill -9 pid or power off) a log file is not moved to oldLogs directory (also when a program is run again) and /var/log/testApp directory may contain many log files.

Is it possible to handle such scenario ?


Solution

  • Is it possible to handle such scenario ?

    Only with offline means. For example, you could auto-run a script on the next boot time to move the half-written log files to the target directory. Or you could do this the next time your application starts. Boost.Log can help you in this case if you open the log files in append mode (i.e. by passing keywords::open_mode = std::ios::app named parameter to the sink constructor) and then immediately call rotate_file on the sink backend. This way non-empty log files will get rotated on your application startup, although you won't be able to actually append to the log files.

    Update:

    I've noticed that you're using a timestamp in your log file name. In this case the approach with rotating the log file with Boost.Log won't work because the library will likely open a differently named file next time your application starts. If timestamps are essential, the only alternative left is a script.