The new Certification Class of REST With Spring is out:


1. Overview

The Log4j 2 library has added support for Java 8 lambda expressions since version 2.4. These expressions can be used by the Logger interface to enable lazy logging.

Let’s see a quick example of how we can make use of this feature.

For more information on Log4j 2, also check out our introductory article.

2. Lazy Logging with Lambda Expressions

A potential performance improvement for applications that use logging can result from avoiding the calculation of log messages if the corresponding log level is not enabled.

First, let’s see a simple log statement at TRACE level:

logger.trace("Number is {}", getRandomNumber());

In this example, the getRandomNumber() method is called to substitute the log message parameter regardless of whether TRACE statements are displayed or not. For example, if the log level is set to DEBUG, log4j 2 will not log the message, but the getRandomNumber() method still runs.

In other words, the execution of this method may be unnecessary.

Before the addition of support for lambda expressions, we could avoid constructing messages which are not logged by explicitly checking the log level before executing the log statement:

if (logger.isTraceEnabled()) {
    logger.trace("Number is {}", getRandomNumer());

In this case, the getRandomNumber() method is only called if the TRACE log level is enabled. This can improve performance depending on how expensive the execution of methods used to substitute parameters is.

By using lambda expressions, we can further simplify the code above:

logger.trace("Number is {}", () -> getRandomNumber());

The lambda expression is only evaluated if the corresponding log level is enabled. This is referred to as lazy logging.

We can also use multiple lambda expressions for a log message:

logger.trace("Name is {} and age is {}", () -> getName(), () -> getRandomNumber());

3. Conclusion

In this quick tutorial, we have seen how we can use lambda expressions with Log4j 2 loggers.

As always, the full source code of the example can be found over on GitHub.

Go deeper into building a REST API with Spring:


Leave a Reply

Be the First to Comment!

Notify of