在使用 Logback 记录计算数据时,我们应该使用 isDebugEnabled() 吗?

Dan*_*ndt 2 java logging logback

尽管在一些教程中,例如这里参数化日志记录部分),说Logback消息{}参数化帮助我们避免日志记录数据中不必要的计算 (如果日志记录级别不是DEBUG):

logger.debug("The bonus for employee {} is {}", 
   employee.getName(), employeeService.calculateBonus(employee));
Run Code Online (Sandbox Code Playgroud)

我测试(在 logback 版本上1.2.3)该优化仅适用于不必要的toString()参数对象 - 因为这适用log4j

Logback文档不包含此细节。

那么,我们必须使用 isDebugEnabled() 来处理所有“昂贵”的日志记录,不是吗?

Dor*_*ray 8

看一下这里的例子

从 2.4 开始,Logger 接口中添加了方法来支持 lambda 表达式。新方法允许客户端代码延迟记录消息,而无需显式检查是否启用了请求的日志级别。例如,以前有人会这样写:

// 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());
 }
Run Code Online (Sandbox Code Playgroud)

在 Java 8 中,使用 lambda 表达式可以达到相同的效果:

// 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());
Run Code Online (Sandbox Code Playgroud)