gpt4 book ai didi

java - 使用 If 子句包围 Logger 以避免冗余的 String 构造

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:15:37 25 4
gpt4 key购买 nike

我得到了在登录 java 时使用此语法的建议:

if (logger.isLoggable(Log.FINE))
{
logger.fine("bla"+" bla"+" bla");
}

这样做的原因是为了避免在日志记录级别低于“FINE”时重复构造参数字符串。 (在上面的示例中 - 5 个冗余字符串对象。(“bla”X3、“bla bla”和“bla bla bla”)。

我想听听其他人对此做了什么,或者您是否认为这有必要。

谢谢!!

最佳答案

一些较新的日志记录框架允许您将参数指定为参数,如果没有日志记录则不会评估它们。

我找到的例子是 LogBack,它是 Log4j 的继承者。这是信息:http://www.infoq.com/news/2007/08/logback

可以这么说,这为您提供了两全其美的体验。优雅的语法和良好的性能。


Log4j 代码示例:

if( logger.isDebugEnabled() ) {
logger.debug( "User with account " +
user.getAccount() + " failed authentication; " +
"supplied crypted password " + user.crypt(password) +
" does not match." );
}

等效的 LogBack 代码:

logger.debug( "User with account {} failed authentication; " +
"supplied crypted password {} does not match.",
user.getAccount(), user.crypt(password) );

This defers the cost of message assembly until LOGBack has ascertained whether or not this message will be viewed. It doesn't defer the cost of retrieving expensive parameters, such as the password crypting in the above example.

关于java - 使用 If 子句包围 Logger 以避免冗余的 String 构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2037543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com