Log4j 2.x如何实现惰性参数评估? [英] How does Log4j 2.x implement lazy argument evaluation?

查看:59
本文介绍了Log4j 2.x如何实现惰性参数评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出 Java参数评估机制 Log4j 2.x 如何实现

我想Log4j的意思是,使用大括号时,他们避免在不需要字符串时构造字符串(例如,Level不是Debug):

使用

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

即使不记录完整消息,也始终会对其进行计算.

使用

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

Log4j可以先检查日志级别,然后决定是否值得构造消息字符串.这样可以节省字符串连接所需的资源.如果消息实际上是在创建的,它将仅在提供的对象上调用toString(),从而节省了进一步的计算成本.

Log4j使用内部类(org.apache.logging.log4j.message.ParameterFormatter),该内部类用提供的参数替换每个{}.它还将捕获toString()引发的异常并报告这些失败.

Given the Java argument evaluation mechanism, how does Log4j 2.x implement lazy evaluation when formatting the message with curly brackets "to avoid the cost of parameter construction" when log is disabled?

e.g.

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

解决方案

I guess what Log4j means, is that with the curly brackets, they avoid constructing a string when its not necessary (e.g. the Level is not Debug):

With

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

the complete message is always computed even when it will not be logged.

With

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

Log4j can check the Log-Level first and then decide if its worth to construct the message string. This saves resources needed for string concatenation. It will only call toString() on the objects supplied if the message is actually being created, saving further computation costs.

Log4j uses an internal class (org.apache.logging.log4j.message.ParameterFormatter) that replaces every {} with the arguments provided. It will also catch exceptions thrown by toString() and report these failures.

这篇关于Log4j 2.x如何实现惰性参数评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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