Search code examples
c++loggingboost

Temporary disable console output for boost::log


I added sink to file via boost::log::add_file_log and console output via boost::log::add_console_log. I am calling a logger via BOOST_LOG_SEV and everything workds perfectely. But there is a place, where a want output only to the file.

How I can disable cosole output in certain place?


Solution

  • You could achieve this with attributes and filters. For example, you could set up a filter in your console sink to suppress any log records that have (or don't have, depending on your preference) a particular attribute value attached.

    boost::log::add_console_log
    (
        ...
        boost::log::keywords::filter = !boost::log::expressions::has_attr("NoConsole")
        ...
    );
    

    Then you could set this attribute in the code region that shouldn't output logs in the console. For example, you could use a scoped attribute:

    BOOST_LOG_SCOPED_THREAD_ATTR("NoConsole", true);
    BOOST_LOG(logger) << "No console output";
    

    You can use whatever method of setting the attribute - as a thread-local attribute, or a logger-specific, it doesn't matter.

    The important difference from temporarily removing the sink is that the solution with attributes will not affect other threads that may be logging while you're suspending console output.