Search code examples
c++boostboost-logboost-logging

How to set open_mode for a boost sink (non global) to append


Currently I'm using sinks for writing data to log files and standard otput. Unfortunately if I restart my application the sink will not append the new entries to the log file. It overrides the existing data. My Code is the following:

using text_sink = boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend>;

Logger::Logger(const LoggerConfig& config):mLoggerConfig(config){

    sink = boost::make_shared<text_sink>();

    if(config.isLogToFile()){
        //sink for output to file
        sink->locked_backend()->add_stream(
                    boost::make_shared<std::ofstream>(mLoggerConfig.getFileName().c_str()));
    }else{
        // create sink to stdout        
        sink->locked_backend()->add_stream(
                    boost::shared_ptr<std::ostream>(&std::cout, empty_delete()));
    }    

    sink->locked_backend()->auto_flush(true);     

    logging::formatter fmt = expr::stream
           << expr::attr< boost::posix_time::ptime >("timeStamp")
           << " " << severityAttr << ": "
           << expr::smessage;

    sink->set_formatter(fmt);

    // register sink
    logging::core::get()->add_sink(sink);

    //sink will only fetch output for this file
    sink->set_filter(expr::has_attr(tagAttr) && tagAttr == mLoggerConfig.getFileName());

    mLogger.add_attribute("fileName", attrs::constant<std::string>(mLoggerConfig.getFileName()));
    mLogger.add_attribute("timeStamp", attrs::local_clock());

}

I found out that there is the keyword open_mode which should be set to append:

boost::log::add_file_log
     (
         boost::log::keywords::file_name = "sample_%Y%m%d.log",
         boost::log::keywords::auto_flush = true,
         boost::log::keywords::open_mode = ( std::ios::out | std::ios::app), //....

But does anybody have an idea how to set this keyword just for the sink in my constructor? Because I guess add_file_log will have a global effect.

Note: I'm not using file rotation.


Solution

  • But does anybody have an idea how to set this keyword just for the sink in my constructor?

    There's no need for the keyword, you can pass the std::ios_base::openmode flags to the std::ofstream constructor.

    //sink for output to file
    sink->locked_backend()->add_stream(boost::make_shared<std::ofstream>(
        mLoggerConfig.getFileName().c_str(), std::ios::out | std::ios::app));
    

    The keyword is needed for the specialized text_file_backend, which manages the file stream by itself.

    Because I guess add_file_log will have a global effect.

    add_file_log is a convenience function that simply creates and adds a new sink to the core. It uses the text_file_backend to implement the sink.