使用{}使用%d或%s的log4j2[英] Log4j2 using {} against using %d or %s

本文是小编为大家收集整理的关于使用{}使用%d或%s的log4j2的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在log4j2中,两者都同样有效,并且不会引起任何比debug更具体的字符串串联?出于任何原因/情况,一个人比另一个人更喜欢吗?

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

{}是否可以与任何类型对象一起使用?

推荐答案

{}符号比%s %d字符串格式符号要高得多. (有基准为此,我稍后再添加一些数字.)

{}符号接受任何对象或原始值,其中%s %d ...字符串格式要求参数的类型匹配格式或异常.因此,通常,{}更方便.

在某些情况下,您想使用字符串格式语法,因为它为您提供了对格式的非常细粒度的控制.如果您想将大量的数字"相当"为1,234,567.123,或控制小数点后面的数字数,则{}还不够.

log4j2允许您混合两个用法.可以到处使用字符串格式语法(通过使用LogManager.getFormattedLogger),但也许更方便的是在大多数情况下使用默认{}格式,并且仅在需要时使用字符串格式语法使用printf方法:

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

内部,使用{}格式log4j2努力避免创建字符串或其他临时对象.字符串格式语法是不可能的.

本文地址:https://www.itbaoku.cn/post/1574980.html

问题描述

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 ?

推荐答案

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.