我在我的应用程序中使用Log4J进行日志记录。之前我使用的调试调用如下:

选项1:

logger.debug("some debug text");

但是一些链接建议最好先检查isDebugEnabled(),比如:

选项2:

boolean debugEnabled = logger.isDebugEnabled();
if (debugEnabled) {
    logger.debug("some debug text");
}

所以我的问题是“选项2是否能提高性能?”

因为在任何情况下Log4J框架对debugEnabled都有相同的检查。对于选项2,如果我们在一个方法或类中使用多个调试语句可能是有益的,这样框架就不需要多次调用isDebugEnabled()方法(每次调用);在这种情况下,它只调用isDebugEnabled()方法一次,如果Log4J被配置为调试级别,那么实际上它会调用isDebugEnabled()方法两次:

如果将值分配给debugEnabled变量,和 实际上由logger.debug()方法调用。

我不认为如果我们在方法或类中编写多个logger.debug()语句并根据选项1调用debug()方法,那么与选项2相比,Log4J框架的开销是很大的。由于isDebugEnabled()是一个非常小的方法(就代码而言),因此它可能是内联的良好候选方法。


当前回答

自从Log4j版本2.4 (orslf4j-api 2.0.0-alpha1)以来,使用流畅的API(或Java 8 lambda对惰性日志的支持)要好得多,支持Supplier<?>为日志消息参数,可以由lambda给出:

log.debug("Debug message with expensive data : {}", 
           () -> doExpensiveCalculation());

OR与slf4j API:

log.atDebug()
            .addArgument(() -> doExpensiveCalculation())
            .log("Debug message with expensive data : {}");

其他回答

Log4j2允许您将参数格式化为消息模板,类似于String.format(),因此不需要执行isDebugEnabled()。

Logger log = LogManager.getFormatterLogger(getClass());
log.debug("Some message [myField=%s]", myField);

简单的log4j2.properties示例:

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d %-5p: %c - %m%n
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = debug
rootLogger.level = info
rootLogger.appenderRef.stdout.ref = STDOUT

截至2。x, Apache Log4j内置了这个检查,所以不再需要isDebugEnabled()。只需执行debug(),如果未启用消息,则消息将被抑制。

使用isDebugEnabled()是为当你通过连接字符串来构建日志消息保留的:

Var myVar = new MyVar();
log.debug("My var is " + myVar + ", value:" + myVar.someCall());

然而,在您的示例中,没有速度增益,因为您只是记录一个字符串,而不执行连接等操作。因此,你只是在给你的代码增加膨胀,让它更难阅读。

我个人在String类中使用Java 1.5格式调用,如下所示:

Var myVar = new MyVar();
log.debug(String.format("My var is '%s', value: '%s'", myVar, myVar.someCall()));

我怀疑是否有很多优化,但它更容易阅读。

不过请注意,大多数日志api都提供了这样开箱即用的格式:例如,slf4j提供了以下格式:

logger.debug("My var is {}", myVar);

这样就更容易阅读了。

Since in option 1 the message string is a constant, there is absolutely no gain in wrapping the logging statement with a condition, on the contrary, if the log statement is debug enabled, you will be evaluating twice, once in the isDebugEnabled() method and once in debug() method. The cost of invoking isDebugEnabled() is in the order of 5 to 30 nanoseconds which should be negligible for most practical purposes. Thus, option 2 is not desirable because it pollutes your code and provides no other gain.

在Java 8中,您不必使用isDebugEnabled()来提高性能。

https://logging.apache.org/log4j/2.0/manual/api.html#Java_8_lambda_support_for_lazy_logging

import java.util.logging.Logger;
...
Logger.getLogger("hello").info(() -> "Hello " + name);