tt0*_*686 7 java lambda java-8 log4j2
我正在阅读Log4j2的新功能,并且有一个功能可以启用
"Java 8 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 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)
在哪里检查是否启用了请求的日志级别?
"logger.isTraceEnabled()"?
在哪里检查是否启用了请求的日志级别?
在logger.trace()方法里面.
这里的诀窍在于你传递参数的方式.pre-java8样式计算调用时的值logger.trace.
logger.trace(..., expensiveOperation());
Run Code Online (Sandbox Code Playgroud)
Java 8风格使用了 Supplier
logger.trace( ..., () -> expensiveOperation());
Run Code Online (Sandbox Code Playgroud)
所以expensiveOperation()只有在请求时才调用它 - 在trace方法内部.
看看实施情况java.util.logging.Logger.log():
public void log(Level level, Supplier<String> msgSupplier) {
if (!isLoggable(level)) {
return;
}
LogRecord lr = new LogRecord(level, msgSupplier.get()); // <-- here is the expensive computation
doLog(lr);
}
Run Code Online (Sandbox Code Playgroud)