Should we use isDebugEnabled() while logging calculated data with Logback?

本秂侑毒 提交于 2020-01-16 08:36:07

问题


Although in some tutorials, for example here (Parametrized logging section), said that Logback message {} parametrization help us to avoid unnecessary calculation in logging data (if logging level is not DEBUG):

logger.debug("The bonus for employee {} is {}", 
   employee.getName(), employeeService.calculateBonus(employee));

I tested (on logback version 1.2.3) that this optimization works only for unnecessary toString() of parameter object - as this works for log4j.

Logback documentation doesn't cover this detail.

So, we have to use isDebugEnabled() for all 'expensive' logging, do we?


回答1:


When you make a method call, e.g. employeeService.calculateBonus(employee), you're calling that method. Simple as that. So you are calculating the employee bonus every time this line is hit. There is no lazy evaluation here.

Whether or not to use log.isDebugEnabled() depends on the situation. In this situation, if that method call is expensive, you should wrap that in a debug enabled check.

In the case of getters, this isn't usually necessary. So, for instance, I would not wrap this in an isDebugEnabled check:

log.debug("Calculating bonus for employee {} {}", employee.firstName(), employee.lastName());

These are simple getters that return a String, so no expensive calculations are done.




回答2:


Take a look at the example here

Since 2.4, methods have been added to the Logger interface to support lambda expressions. The new methods allow client code to lazily log messages without explicitly checking if the requested log level is enabled. For example, previously one would write:

// pre-Java 8 style optimization: explicitly check the log level
// to make sure the expensiveOperation() method is only called if necessary
 if (logger.isTraceEnabled()) {
     logger.trace("Some long-running operation returned {}", expensiveOperation());
 }

With Java 8, the same effect can be achieved with a lambda expression:

// Java-8 style optimization: no need to explicitly check the log level:
// the lambda expression is not evaluated if the TRACE level is not enabled
logger.trace("Some long-running operation returned {}", () -> expensiveOperation());


来源:https://stackoverflow.com/questions/59737916/should-we-use-isdebugenabled-while-logging-calculated-data-with-logback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!