Search code examples
c++loggingboostc++17

How to use Boost::log not to rewrite the log file?


Below is the simple example of using boost::log to write log,

#include <boost/log/trivial.hpp>

namespace logging = boost::log;

logging::add_file_log("sample.log")->set_filter(
    logging::trivial::severity >= logging::trivial::info
);

BOOST_LOG_TRIVIAL(info) << "log content";

Every time run logging::add_file_log("sample.log") would rewrite the log file -- erase the original stuff and write new log. So it can't be used for a multi-process-one-log-file system. How do I set not to rewrite the file?

Edit:

I wrap this boost::log in a dll and attempt to let other exe files to call it.


Solution

  • You can pass an openmode to the setup function:

    Live On Coliru

    #include <boost/log/trivial.hpp>
    #include <boost/log/utility/setup.hpp>
    #include <random>
    
    namespace logging = boost::log;
    namespace logkw = logging::keywords;
    
    int main()
    {
        logging::add_file_log("sample.log", logkw::open_mode = std::ios::app)
            ->set_filter(                                            //
                logging::trivial::severity >= logging::trivial::info //
            );
    
        std::mt19937 mt(std::random_device{}());
    
        BOOST_LOG_TRIVIAL(info) << "log content " << std::uniform_int_distribution(5,50)(mt);
    }
    

    Prints e.g.

    log content 33
    log content 14
    log content 39
    log content 39
    log content 46