Ignore exceptions on Boost.Log when unable to create folder

Viewed 68

This is a snippet of code that I have to maintain:

std::string log_file_name = "/tmp/log/program.log";    
auto fs_sink = boost::log::add_file_log( boost::log::keywords::file_name = log_file_name, boost::log::keywords::open_mode = std::ios_base::app );

boost::log::add_common_attributes( );
fs_sink->locked_backend( )->auto_flush( true );

BOOST_LOG_TRIVIAL(info) << "Program Init...";

It's works fine, but when the program is unable to create the /tmp/log/ folder (e.g: there is already a file called /tmp/log), it throws an exception in BOOST_LOG_TRIVIAL

Error - Terminating - Exception: boost::filesystem::create_directory: Not a directory: "/tmp/log"
terminate called after throwing an instance of 'boost::filesystem::filesystem_error'
  what():  boost::filesystem::create_directory: Not a directory: "/tmp/log"

Is it possible to gracefully ignore when such a situation happens, without throwing an exception?

2 Answers

You can set an exception handler on sink, core or logger level. The handler will be called when an exception is propagated through the given component, and in particular it may suppress further propagation of the exception. For example, to suppress all exceptions on the core level, you can set it like this:

boost::log::core::get()->set_exception_handler(boost::log::make_exception_suppressor());

After discussing this with a coworker, he came up with this arguably elegant solution. On the first BOOST_LOG_TRIVIAL line, we check for exceptions, and if there was a problem, we disable the file backend to gracefully ignore future errors.

try
{
    BOOST_LOG_TRIVIAL(info) << "Program Init...";
}
catch( ... )
{
    // Disable file backend
    boost::log::core::get( )->remove_all_sinks( );
}

After doing this, by default all logs will go to stdout.

Related