Temporary disable console output for boost::log

Viewed 381

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?

2 Answers

You can easely do it with remove_sink() function.

console_sink = boost::log::add_console_log(std::cout);
boost::log::core::get()->remove_sink(console_sink);

After that you can call an add_console_log() again and enable console output.

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.

Related