I am using SLF4J with Logback in a Spring Boot application. I was interested in using lazy logging and after some research, I came up with this solution.
This works as expected and does not invoke methods if the logging level is not matched.
logger.debug("Begin proceed aspect Method {} : initiator={} | recepient={} | tx_type={}",
new Object() {@Override public String toString() { return proceedingJoinPoint.getSignature().getName(); }},
new Object() {@Override public String toString() { return request.getAgentAlias(); }},
new Object() {@Override public String toString() { return request.getSubscriberMobile(); }},
new Object() {@Override public String toString() { return request.getTxType(); }});
As you can see, I am creating new Objects and overriding the toString method over and over. I don't want to do this. Is there a better way to do this?
I am using the SLF4J 1.7.28 version which came bundled with Spring Boot starter. Please note I prefer using the SLF4J over other logging frameworks.
I tried slf4j-api 2.0.0-alpha1 version along with slf4j-simple binding since it has logger.atDebug.log() implementation. But I couldn't make it work properly.
Thank you.
If you like to add some condition lines, you could add an if statement to check if the log level is enabled and then log the message.
Lazy loading is preserved but you're going to get something like: