Search code examples
c++boost

Ignore exceptions on Boost.Log when unable to create folder


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?


Solution

  • 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());