I use several severity_channel_logger_mt
instances throughout the project with different "Channel" attributes. However, for one specific log line, I'd like to set the "Channel" attribute directly in the call. Using the macro BOOST_LOG_CHANNEL_SEV(logger, channel, severity)
, this is actually not difficult to do. However, this changes the "Channel" attribute. Subsequent logging calls will not use the initial channel attribute, but the changed one from the last logging call.
The only way I found to change the channel attribute back to the original value is: to mis-use the open_record()
function of the logger object.
My Question: is there a more elegant way of doing this? Is there perhaps a specific function that allows setting attributes of a logger directly?
Code snippet to highlight the procedure:
auto & lg = global_logger::get();
BOOST_LOG_CHANNEL_SEV(lg, "test-subsystem", exec_severity) << "Message 1";
// misuse the open_record call to set the channel attribute
// reset channel name back to "global"
auto rc = lg.open_record(boost::log::keywords::channel = "global" );
rc.reset(); // attempt to clean-up a bit
BOOST_LOG_CHANNEL(lg, exec_severity) << "Message 2";
In the above example, "Message 1" shall come from "test-subsystem", but the other messages shall come from "global" channel. If the open_record()
and rc.reset();
lines are commented out, both messages come from the "test-system"
Update:
I ended up implementing a slightly different solution
BOOST_LOG_CHANNEL_SEV()
to log to this logger which takes an argument to set the "Channel" name on each callThe updated code snippet from above looks like this:
auto & stlog = global_logger::get();
auto & lg = special_logger::get();
BOOST_LOG_CHANNEL_SEV(lg, "test-subsystem", exec_severity) << "Message 1";
// this log line will be in channel "global" again
BOOST_LOG_SEV(stlog, exec_severity) << "Message 2";
is there a more elegant way of doing this?
As you can see in the channel feature reference section, there is a channel
method, which can be used to set the channel name. This method is inherited by the logger.
However, it is generally advised to avoid modifying the channel name for performance reasons. When you have multiple distinct subsystems with corresponding channel names it is better to dedicate a separate logger for each subsystem. Otherwise you're paying performance overhead for setting channel name on each log record along with the necessary thread synchronization.