rewrite-logging-frameworks
rewrite-logging-frameworks copied to clipboard
Recipe to put expensive logger parameters into lambdas/conditionals
Sometimes parameters to logging invocations include expensive computations which are pointless if the log level isn't set such that the message will actually be recorded.
It would be useful to have a recipe to remediate this. In slf4j 1 or 2 you can wrap the expensive logging statement in a conditional like so:
if (logger.isDebugEnabled()) {
logger.debug("Something important {}", objectMapper.writeValueToString(object));
}
In slf4j 2 there is the option of wrapping the expensive parameter in a lambda:
logger.debug("Something important {}", () -> objectMapper.writeValueAsString(object));
Note that in this case checks would have to be made that all identifiers in lambda were final or effectively final, per Java's rules about what data may be included in a closure.
I believe there is an RSPEC number for this but I do not know what it is.