Log4j2 using {} against using %d or %s

前端 未结 1 1422
遥遥无期
遥遥无期 2021-02-19 15:47

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 b

1条回答
  •  伪装坚强ぢ
    2021-02-19 16:43

    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.

    0 讨论(0)
提交回复
热议问题