Search code examples
c++boostboost-log

Can I copy a Boost::Log sink and change it?


I'm currently creating a log sink that dumps log lines from the output of my Trainer class to cout:

    using namespace boost;                                                      
    using namespace log;                                                        
    using namespace expressions;                                                
    using namespace sinks;                                                      

    auto sink = make_shared<synchronous_sink<text_ostream_backend>>();          

    sink->set_formatter(Utility::GetLoggingFormat());                           

    sink->locked_backend()->add_stream(                                         
        shared_ptr<std::ostream>(&std::cout, null_deleter()));                  
    sink->set_filter((                                                          
        has_attr(Utility::ClassTag) &&                                          
        Utility::ClassTag == "App::Trainer"));                                  
    boost::log::core::get()->add_sink(sink);                                    

However, I have already added a sink (by calling add_file_log elsewhere) that dumps all log lines to a file. It uses the same GetLoggingFormat() formatter. In fact, the only reason I have that function is so that I don't have to repeat the formatter code.

Instead, I'd prefer to just "copy" the file sink (created elsewhere with add_file_log), change its output to std::cout and add the filter to it.

Can I do this?


Solution

  • No, that cannot be done. Sinks cannot be copied, and in fact the sinks created by add_file_log are using not text_ostream_backend but text_file_backend; you cannot configure text_file_backend to output to std::cout.

    Your best approach is to either use a function, like you already do, or cache the formatter in a formatter object and set it to both your sinks.