如何在logger语句中检测字符串连接?

Che*_*rry 5 java findbugs checkstyle pmd maven

有没有办法配置Checkstyle,PMD或FindBugs Maven插件来检测这样的代码:

logger.debug("string" + stringVariable);
Run Code Online (Sandbox Code Playgroud)

代替:

logger.debug("format string {}", stringVariable);
Run Code Online (Sandbox Code Playgroud)

Sla*_*hin 5

好问题!

我刚发现的附加规则FindBugs的集合覆盖你的情况(有的更多):https://github.com/eller86/findbugs-slf4j

检查SLF4J_FORMAT_SHOULD_BE_CONST应该允许您在格式字符串中查找字符串连接.


Pra*_*ran -1

这样做。

参考String.format()

logger.debug(String.format("format string %s ", stringVariable));
Run Code Online (Sandbox Code Playgroud)

或者

参考MessageFormat.format()

logger.debug(MessageFormat.format("format string {0}", new Object[]{stringVariable }));
Run Code Online (Sandbox Code Playgroud)

  • 呃!两个注释: 1)带有“+”的字符串连接通常使用 StringBuilder 进行编译,有时这是可以接受的。在这种情况下使用 String.format 会使情况变得更糟,因为这种格式比简单的串联更复杂。2)问题是如何检测记录器调用中的字符串连接,而不是如何更好地处理它们。事实上,这个问题已经包含了一个记录器的示例,它已经实现了格式化。 (7认同)