在使用Logback记录计算的数据时,我们应该使用isDebugEnabled()吗? [英] Should we use isDebugEnabled() while logging calculated data with Logback?

查看:297
本文介绍了在使用Logback记录计算的数据时,我们应该使用isDebugEnabled()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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));

我测试了(在Logback版本1.2.3上)此优化仅适用于不必要的参数对象toString()-因为此 表示 log4j .

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 文档没有涵盖此细节.

Logback documentation doesn't cover this detail.

因此,我们必须对所有昂贵"的日志记录使用isDebugEnabled(),对吗?

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

推荐答案

看看示例从2.4开始,已将方法添加到Logger接口以支持lambda表达式.新方法允许客户端代码懒惰地记录消息,而无需显式检查是否启用了请求的日志级别.例如,以前一个会写:

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());
 }

使用Java 8,可以通过lambda表达式实现相同的效果:

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());

这篇关于在使用Logback记录计算的数据时,我们应该使用isDebugEnabled()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆