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

查看:709
本文介绍了使用{}的Log4j2反对使用%d或%s的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Log4j2中,以下两种方法是否同样有效,并且不会导致日志级别比DEBUG更具体的任何字符串连接?并且由于任何原因/情况,一个人会比其他人更受青睐吗?

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 ?

推荐答案

{}表示法比%s %d String格式表示法有效得多. (有

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

{}表示法接受任何对象或原始值,其中%s %d ...字符串格式要求参数的类型与该格式匹配,否则将引发异常.因此,通常{}更方便.

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.

在某些情况下,您想使用String格式语法,因为它可以使您对格式进行非常细粒度的控制.如果要漂亮地打印"大量数字作为1,234,567.123,或控制小数点后的位数,则{}是不够的.

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允许您混合使用两种用法.可以在任何地方使用String格式语法(通过使用LogManager.getFormattedLogger),但是也许更方便的是大多数时候使用默认的{}格式,并且仅在需要细粒度控制时才使用String格式语法使用printf方法:

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());

内部,采用{}格式,Log4j2努力避免创建字符串或其他临时对象.使用String格式语法无法做到这一点.

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.

这篇关于使用{}的Log4j2反对使用%d或%s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆