简体   繁体   English

ArchUnit 可以在方法调用中检查某些字符串模式吗?

[英]Can ArchUnit check for certain string patterns in method calls?

In our code we again and again have the issue that somebody forgot to adapt the usage of placeholders when switching between the use of the logger and String.format(...) methods.在我们的代码中,我们一次又一次地遇到一个问题,即在使用 logger 和 String.format(...) 方法之间切换时,有人忘记调整占位符的使用。

For log statements one has to use '{}' as placeholders, like so:对于日志语句,必须使用“{}”作为占位符,如下所示:

logger.info("File {} successfully opened: {} bytes read, {} objects created", file, nrBytes, nrObjects); 

But when using String.format(...) to compose a message one has to use '%s' as placeholders for strings and the statement has to read:但是,当使用 String.format(...) 编写消息时,必须使用 '%s' 作为字符串的占位符,并且语句必须阅读:

logger.info(String.format("File %s successfully opened: %s bytes read, %s objects created", file, nrBytes, nrObjects)); 

The second form is often used, when logging an error where the second argument is the Throwable that one wants to log.在记录错误时,通常使用第二种形式,其中第二个参数是要记录的 Throwable。

Too often people forget about this details and then we end up with wrong log statements that output nothing reasonable.人们经常忘记这些细节,然后我们最终得到错误的日志语句,即 output 没有任何合理性。

I know and agree that this is absolutely not an architecture issue but rather a simple programming error, but it would be great if one could (ab-)use ArchUnit to check for the use of '%s' (or the absence of '{}') in the first String argument of the String.format() -method.我知道并同意这绝对不是架构问题,而是一个简单的编程错误,但如果可以(ab-)使用 ArchUnit 来检查 '%s' 的使用(或缺少 '{ }') 在String.format()方法的第一个 String 参数中。 Is something like that possible?这样的事情可能吗?

The ArchUnit, currently in version 0.16.0, does not analyze parameter values for method calls. ArchUnit,当前版本为 0.16.0,不分析方法调用的参数

The sonar rule "Printf-style format strings should be used correctly" might however catch these bugs.然而,声纳规则“应该正确使用 Printf 样式的格式字符串”可能会捕获这些错误。

As already noted ArchUnit can't do this - PMD's [invalidlogmessageformat][1] rule is useful though (and I find PMD easier to deal with than sonar).如前所述,ArchUnit 无法做到这一点——PMD 的 [invalidlogmessageformat][1] 规则很有用(而且我发现 PMD 比声纳更容易处理)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM