避免字符串连接大型日志消息

abh*_*eep 1 java log4j slf4j

使用像 slf4j 这样的东西的优点之一是它通过使用参数化日志来避免字符串连接。但是,当您有很长的日志消息时,如何避免性能下降?

logger.debug("This is a very long message that prints two values." +
    " However since the message is long, we still incur the performance hit" +
    " of String concatenation when logging {} and {} ", value1, value2);
Run Code Online (Sandbox Code Playgroud)

有没有办法避免这种性能成本,而不使用丑陋的 if 块来检查日志级别?

 if (logger.isDebugEnabled()) {
     logger.debug("This is a very long message that prints two values." +
         " However since the message is long, we still incur the performance hit" +
         " of String concatenation when logging {} and {}", value1, value2);
 }
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 5

没有字符串连接。

编译器将为您创建一个长字符串文字。

  • @Rogue 这取决于你做了多少日志记录。 (2认同)