Java lambda expressions and logging

I'm reading the new features of log4j2, and there is a feature that can be enabled

"Java 8 lambda supports lazy logging"

It gives two examples

The first is bad practice

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

The second is good practice

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

Where can I check if the requested log level is enabled? “logger.isTraceEnabled()”?

Solution

In logger In the trace() method

The trick here is the way you pass parameters Pre-java8 style calculation calls logger The value of trace

logger.trace(...,expensiveOperation());

Using supplier in Java 8 style

logger.trace( ...,() -> expensiveOperation());

Therefore, expensiveoperation () is called only on request - in the trace method

Look at Java util. logging. Logger. Implementation of 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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>