简体   繁体   English

log4j v2格式化功能

[英]log4j v2 formatting capabilities

In case of loggers its said that for every logger there is hidden cost of parameter construction . 在记录器的情况下,它表示对于每个记录器都存在参数构造的隐藏成本。

eg:- 例如:-

 logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i]));

This incurs the cost of constructing the message parameter, ie converting both integer i and entry[i] to a String, and concatenating intermediate strings, regardless of whether the message will be logged or not. 这会导致构造消息参数的成本,即将integer i和entry [i]都转换为String,并连接中间字符串,无论是否记录消息。 This cost of parameter construction can be quite high and it depends on the size of the parameters involve. 参数构造的成本可能非常高,并且取决于所涉及的参数的大小。

On log 4j site its given that The best approach to avoid the cost of parameter construction is to use Log4j 2's formatting capabilities. 在log 4j site上给出了避免参数构造成本的最佳方法是使用Log4j 2的格式化功能。 For example, instead of the above write: 例如,而不是上面写的:

logger.debug("Entry number: {} is {}", i, entry[i]);

Whats happening inside this formatting capability that cost incurred this time will be less. 在这种格式化功能中发生的事情会产生这样的成本。 Is it not creating strings like it used to create in previous cases. 是不是像以前的情况那样创建字符串。 please someone explain this? 请有人解释一下吗?

In the first example, it is creating the String even if not needed. 在第一个示例中,即使不需要,也会创建String。 However, if it is needed this is likely to be the most efficient way. 但是,如果需要,这可能是最有效的方式。 BTW The String.valueOf is redundant. BTW String.valueOf是多余的。

The second option is faster if the message is turned off. 如果消息关闭,第二个选项会更快。 This avoid creating a String which is later discarded because it can check whether debugging is enabled before building the String. 这样可以避免创建一个稍后被丢弃的String,因为它可以在构建String之前检查是否启用了调试。 Note: if you do need the String, it is likely to be slower as it has to parse the message format. 注意:如果确实需要String,则可能会因为必须解析消息格式而变慢。

The best of both worlds, but the wordest is 这两个世界中最好的,但最令人担忧的是

if(logger.isDebugEnabled())
    logger.debug("Entry number: " + i + " is " + entry[i]);

In this case, you do the check and if it is to be logged, get the fastest message generation. 在这种情况下,您进行检查,如果要记录,请获取最快的消息生成。


There are logging frameworks which avoid creating any String and are fast enough you don't need to turn debugging off in the first place, but these are not simple to use, and I would avoid them unless you need more performance. 有一些日志框架可以避免创建任何字符串并且速度足够快,您不需要首先关闭调试,但这些框架使用起来并不简单,除非您需要更高的性能,否则我会避免使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM