我们应该在使用 Logback 记录计算数据时使用 isDebugEnabled() 吗?
Should we use isDebugEnabled() while logging calculated data with Logback?
虽然在一些教程中,例如here(参数化日志记录部分),说Logback消息{}
参数化帮助我们避免记录数据中不必要的计算(如果记录级别不是 DEBUG):
logger.debug("The bonus for employee {} is {}",
employee.getName(), employeeService.calculateBonus(employee));
我测试了(在 logback 版本 1.2.3
上)这个优化只对参数对象的不必要的 toString()
有效——因为这个 works 对于 log4j.
Logback documentation 不包括这个细节。
所以,我们必须对所有 'expensive' 日志记录使用 isDebugEnabled(),对吗?
当您进行方法调用时,例如employeeService.calculateBonus(employee)
,您正在调用该方法。就那么简单。因此,每次命中此行时,您都在计算员工奖金。这里就不懒评价了
要不要用log.isDebugEnabled()
要看情况。在这种情况下,如果该方法调用很昂贵,您应该将其包装在启用调试的检查中。
对于 getter,这通常不是必需的。因此,例如,我不会将其包装在 isDebugEnabled
检查中:
log.debug("Calculating bonus for employee {} {}", employee.firstName(), employee.lastName());
这些是 return 和 String
的简单吸气剂,因此无需进行昂贵的计算。
看例子here
从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());
}
用Java8,用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());
虽然在一些教程中,例如here(参数化日志记录部分),说Logback消息{}
参数化帮助我们避免记录数据中不必要的计算(如果记录级别不是 DEBUG):
logger.debug("The bonus for employee {} is {}",
employee.getName(), employeeService.calculateBonus(employee));
我测试了(在 logback 版本 1.2.3
上)这个优化只对参数对象的不必要的 toString()
有效——因为这个 works 对于 log4j.
Logback documentation 不包括这个细节。
所以,我们必须对所有 'expensive' 日志记录使用 isDebugEnabled(),对吗?
当您进行方法调用时,例如employeeService.calculateBonus(employee)
,您正在调用该方法。就那么简单。因此,每次命中此行时,您都在计算员工奖金。这里就不懒评价了
要不要用log.isDebugEnabled()
要看情况。在这种情况下,如果该方法调用很昂贵,您应该将其包装在启用调试的检查中。
对于 getter,这通常不是必需的。因此,例如,我不会将其包装在 isDebugEnabled
检查中:
log.debug("Calculating bonus for employee {} {}", employee.firstName(), employee.lastName());
这些是 return 和 String
的简单吸气剂,因此无需进行昂贵的计算。
看例子here
从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());
}
用Java8,用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());