带有If子句的Sorrounding Logger,以避免冗余的String构造

Ben*_*Ben 6 java logging

登录java时,我建议使用此语法:

if (logger.isLoggable(Log.FINE))
{
    logger.fine("bla"+" bla"+" bla");
}
Run Code Online (Sandbox Code Playgroud)

这样做的原因是为了避免参数字符串的冗余构造,因为日志记录级别低于"FINE".(在上面的例子中 - 5个冗余的字符串对象.("bla"X3,"bla bla"和"bla bla bla").

我想听听其他人正在做些什么,或者你认为这是必要的.

谢谢!!

Car*_*icz 6

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

我找到的例子是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." );
}
Run Code Online (Sandbox Code Playgroud)

等效LogBack代码:

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

这延迟了消息组装的成本,直到LOGBack确定是否将查看此消息.它不会推迟检索昂贵参数的成本,例如上例中的密码加密.