虽然在一些教程中,例如 here (参数化日志部分),说Logback消息{}
参数化帮助我们避免日志数据中不必要的计算(如果日志级别不是DEBUG) ):
logger.debug("The bonus for employee {} is {}",
employee.getName(), employeeService.calculateBonus(employee));
我测试过(在 logback 版本 1.2.3
上),此优化仅适用于参数对象的不必要的 toString()
- 就像这个 works对于log4j。
登录documentation不涉及此细节。
那么,我们必须使用 isDebugEnabled() 来处理所有“昂贵”的日志记录,是吗?
最佳答案
看一下示例 here
自 2.4 起,Logger 接口(interface)中添加了方法以支持 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());
}
使用 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());
关于java - 在使用 Logback 记录计算数据时,我们应该使用 isDebugEnabled() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737916/