我正在阅读Log4j2的新功能,并且有一个功能可以启用
它给出了两个例子
第一个是不好的做法
// 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 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());
在哪里检查是否启用了请求的日志级别?
“logger.isTraceEnabled()”?
解决方法
Where is being made the checking if the requested log level is enabled ?
在logger.trace()方法中.
这里的诀窍在于你传递参数的方式. pre-java8样式计算调用logger.trace时的值.
logger.trace(...,expensiveOperation());
Java 8样式使用Supplier
logger.trace( ...,() -> expensiveOperation());
因此,仅在请求时调用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); }