Log4j2 using {} against using %d or %s

老子叫甜甜 提交于 2019-12-08 17:05:27

问题


In Log4j2, are both the following equally efficient and do not cause any string concatenation with a log level more specific than DEBUG ? And for any reason/situation will one be preferred over other ?

log.warn(String.format("Number of cars : %d",carCount));
log.warn("Number of cars : {}",carCount );

And does {} works with any type of Object ?


回答1:


The {} notation is much more efficient than the %s %d String format notation. (There are benchmarks for this, I'll add some numbers later.)

The {} notation accepts any Object or primitive value, where the %s %d ... String format requires that the type of the parameter matches the format or an exception is thrown. So generally, {} is more convenient.

There are cases where you want to use the String format syntax, since it gives you very fine-grained control over the formatting. If you want to "pretty-print" a large number as 1,234,567.123, or control the number of digits behind the decimal point, then {} is not enough.

Log4j2 allows you to mix both usages. It is possible to use the String format syntax everywhere (by using LogManager.getFormattedLogger), but perhaps more convenient is to use the default {} format most of the time, and only use the String format syntax when you need the fine grained control with the printf method:

logger.printf(Level.INFO, "Logging in user %1$s with birthday %2$tm %2$te,%2$tY", user.getName(), user.getBirthdayCalendar());

Internally, with the {} format Log4j2 makes an effort to avoid creating Strings or other temporary objects. This is not possible with the String format syntax.



来源:https://stackoverflow.com/questions/41532840/log4j2-using-against-using-d-or-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!