How does Log4j implement lazy argument evaluation?

假装没事ソ 提交于 2019-12-21 07:16:39

问题


Given the Java argument evaluation mechanism, how does Log4j 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]);

回答1:


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 String is always calculated even when its not 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.

Log4j uses a internal Class (org.slf4j.helpers.MessageFormatter) that replaces every {} with the arguments provided. You can have a look at the Sourcecode in org.slf4j.impl.Log4jLoggerAdapter.debug(String, Object[])



来源:https://stackoverflow.com/questions/32183966/how-does-log4j-implement-lazy-argument-evaluation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!