更强大的参数格式化
API模块和slf4j相比,提供了更丰富的参数格式化功能。
使用{}占位符格式化参数
在slf4j里,我们可以用{}的方式来实现“format”的功能(参数会直接to
String替换占位符),像下面这样:
logger.debug("Logging in user {} with birthday {}", user.getName(), user.get
BirthdayCalendar());
使用String.format的形式格式化参数
log4j2 中除了支持{}的参数占位符,还支持String.format的形式:
public static Logger logger = LogManager.getFormatterLogger("Foo");
logger.debug("Logging in user %s with birthday %s", user.getName(), user.get
BirthdayCalendar());
logger.debug("Logging in user %1$s with birthday %2$tm %2$te,%2$tY", user.ge
tName(), user.getBirthdayCalendar());
logger.debug("Integer.MAX_VALUE = %,d", Integer.MAX_VALUE);
logger.debug("Long.MAX_VALUE = %,d", Long.MAX_VALUE);
**
注意,如果想使用String.format的形式,需要使用LogManager.getForm
atterLogger而不是LogManager.getLogger**
使用logger.printf格式化参数
log4j2 的
Logger接口中,还有一个printf方法,无需创建LogManager.getFormat
terLogger,就可以使用String.format的形式
logger.printf(Level.INFO, "Logging in user %1$s with birthday %2$tm %2$te,%2
$tY", user.getName(), user.getBirthdayCalendar());
logger.debug("Opening connection to {}...", someDataSource);
“惰性”打日志(lazy logging)