1. Overview
1.概述
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.
Log4j 2库从2.4版本开始增加了对Java 8 lambda表达式的支持。这些表达式可以被Logger接口使用,以实现懒人日志。
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.
有关Log4j 2的更多信息,还请查看我们的介绍性文章。
2. Lazy Logging With Lambda Expressions
2.使用Lambda表达式的懒惰日志
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:
首先,让我们看看TRACE级别的简单日志语句。
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.
在这个例子中,无论是否显示TRACE语句,都会调用getRandomNumber()方法来替代日志消息参数。例如,如果日志级别被设置为DEBUG,log4j 2将不会记录消息,但getRandomNumber()方法仍然运行。
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:
在增加对lambda表达式的支持之前,我们可以通过在执行日志语句之前显式地检查日志级别来避免构建不被记录的消息。
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.
在这种情况下, getRandomNumber()方法只有在TRACE日志级别被启用时才会被调用。这可以提高性能,这取决于用于替代参数的方法的执行成本有多高。。
By using lambda expressions, we can further simplify the code above:
通过使用lambda表达式,我们可以进一步简化上述代码。
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.
只有当相应的日志级别被启用时,才会对lambda表达式进行评估。这被称为懒惰日志。
We can also use multiple lambda expressions for a log message:
我们也可以为一条日志信息使用多个lambda表达式。
logger.trace("Name is {} and age is {}", () -> getName(), () -> getRandomNumber());
3. Conclusion
3.结论
In this quick tutorial, we have seen how we can use lambda expressions with Log4j 2 loggers.
在这个快速教程中,我们已经看到了如何在Log4j 2记录器中使用lambda表达式。
As always, the full source code of the example can be found over on GitHub.
一如既往,该示例的完整源代码可以在GitHub上找到over。