I have some trivial logging:
BOOST_LOG_TRIVIAL(trace) << make_trace_record();
Now make_trace_record
is a somewhat expensive function to call (don't ask why, it's complicated). I want to call it only if the log currently passes filtering. How can I do that? I don't see a way to call the severity filter explicitly.
Boost.Log filters beforehand; therefore,
make_trace_record()
will not be called if the severity is not high enough.In order to set the severity filter for the trivial logger, call:
For instance, the following example outputs
1
, showing thatexpensive()
is only called once:Live On Coliru
Prints:
For those wondering how it works, take a look to: How does the "lazy evaluation" of Boost Log's trivial loggers work?
I would do this with an intermediate class who's ostream operator lazily calls your function.
Something like this:
Acorn's answer correctly points out that Boost.Log macros already implement conditional execution of the streaming expression. This behavior is documented in the Tutorial.
I will add that you can generate log records manually, avoiding the macros. An example is given here:
This can be useful if log message formatting is complicated and doesn't fit easily in a streaming expression.