In release 2.4, the Logger interface added support for lambda expressions. Such that, Log4j2 loggers can also take in a message supplier that will be lazily evaluated, here is the signature for the info one:
@Override
public void info(final Supplier<?> messageSupplier) {
logIfEnabled(FQCN, Level.INFO, null, messageSupplier, (Throwable) null);
}
This allows client code to lazily log messages without explicitly checking if the requested log level is enabled. For example, previously you would write:
// 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());
}
With Java 8 and above you can achieve the same effect with a lambda expression. You no longer need to explicitly check the log level:
// 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());
For Kotlin, there is a Kotlin logging facade based on Log4j 2 in which the signature is as follow:
fun info(supplier: () -> Any?) {
delegate.logIfEnabled(FQCN, Level.INFO, null, supplier.asLog4jSupplier(), null)
}
And here is a usage example:
logger.info { "This is a log event" }
Both will avoid the cost of parameter construction.