Have you seen something like below in your application, and ever wondered about the overhead (due to the if condition). This post covers ways to get rid of the overhead with Log4j 2.x and Java 8.
if(log.isDebugEnabled()){
log.debug("Person="+ person);
}
Above style is quite common in log4j-1.x; though it adds few extra lines it improves the performance.
Below log calls toString method on the person even if it's not going to get logged.
So how do we remove the overhead of if check
The if condition is an overhead and it's going to appear multiple places in method/class. Also, if you don't do logging judiciously then it can be spread all over.
log4j 2.x
log4j 2.x is out there after a long gap and this particular issue has been addressed. Inspired by SLF4J it has added parameterized logging.
log.debug("{}"+person); //will not call .toString method on person
log.debug("{}"+person.toString()); //this is still going to be an issue
So log4j 2.x parameterized logging mechanism will not call implicit (toString) method on the person, but if you call it explicitly then it will make the call. So log4j 2 has partially addressed the problem.
log4j 2.4 + Java 8 lambda
log.debug(() -> person.toString()); //all good
log.debug("{}"+ this::expensiveOperation()); //all good
Final Note:
Be mindful of logging overhead when you do code review!
log4j 2.x
log4j 2.x is out there after a long gap and this particular issue has been addressed. Inspired by SLF4J it has added parameterized logging.
log.debug("{}"+person); //will not call .toString method on person
So log4j 2.x parameterized logging mechanism will not call implicit (toString) method on the person, but if you call it explicitly then it will make the call. So log4j 2 has partially addressed the problem.
log4j 2.4 + Java 8 lambda
log4j 2.4 supports lambda based mechanism which solves the problem completely. So it doesn't call the method (implicit or explicit) at all if the statement being logged is at the level less specific than the current level.
log.debug(() -> person.toString()); //all good
log.debug("{}"+ this::expensiveOperation()); //all good
Final Note:
Be mindful of logging overhead when you do code review!
References
https://logging.apache.org/log4j/2.0/manual/api.html
http://marxsoftware.blogspot.pt/2015/10/log4j2-non-logging-performance.html
http://www.jroller.com/bantunes/entry/java_lazy_logging_features_ways
http://www.infoq.com/news/2014/07/apache-log4j2
http://www.grobmeier.de/log4j-2-performance-close-to-insane-20072013.html
No comments:
Post a Comment