Log4J2:替换参数无法正常工作
Log4J2: Substituting Parameters does not work properly
我正在使用 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()
和 expensiveOperation()
这两个方法都不会被调用。我做错了什么吗?
根据设置的日志级别过滤日志(处理程序将仅接收过滤后的日志)。但是 jvm 确实会执行每个日志。
我正在使用 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()
和 expensiveOperation()
这两个方法都不会被调用。我做错了什么吗?
根据设置的日志级别过滤日志(处理程序将仅接收过滤后的日志)。但是 jvm 确实会执行每个日志。