java - Log4J2:替换参数无法正常工作

标签 java logging parameters log4j2 substitution

我使用 Log4J 2.8.2。

手册( https://logging.apache.org/log4j/2.0/manual/api.html )说用占位符替换参数效果更好:

这意味着

logger.debug("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar());

更好
if (logger.isDebugEnabled()) {
    logger.debug("Logging in user " + user.getName() + " with birthday " + user.getBirthdayCalendar());
}

因为:

the logging level will only be checked once and the String construction will only occur when debug logging is enabled.

所以可以说我有以下两种方法:

public static String getSentence() {
        System.out.println("Sentence Invoked!");
        return "{} im the Best!";
    }

    public static String expensiveOperation() {
        System.out.println("Expensive Invoked!");
        return "John Doe";
    }

现在 rootLogger 的级别设置为 INFO。如果我按以下方式登录:

LOGGER.debug(getSentence(), expensiveOperation());

我得到以下输出:

Sentence Invoked!
Expensive Invoked!

这意味着这两个方法都会被调用,尽管没有发生日志记录,因为 LOGGER 的级别是 DEBUG 而 rootLoggers 的级别是 INFO

我预计 getSentence()exppressiveOperation() 方法都不会被调用。我是不是做错了什么?

最佳答案

根据设置的日志级别过滤日志(Handler只会接收过滤后的日志)。但jvm确实执行了每条日志。

关于java - Log4J2:替换参数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49478502/

相关文章:

Java:基本的 OOP 问题

java - Spliterator 中 estimatedSize 和 getExactSizeIfKnown 的区别

c++ - 错误无效使用 void 表达式。试图将参数传递给函数

java - 查找文件保存的正确参数

php - 如何配置 Apache Kafka 来集中应用程序日志?

c++ - 结构作为C++中的参数

java - 如何在 Eclipse 中指定嵌套泛型

Java延迟帧重画

logging - Kibana 以 JSON 格式记录到 Syslog

logging - 日志不打印完整的堆栈跟踪