我使用 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/