mmo
mmo

Reputation: 4214

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.

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:

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.

Too often people forget about this details and then we end up with wrong log statements that output nothing reasonable.

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. Is something like that possible?

Upvotes: 0

Views: 455

Answers (2)

JosephH
JosephH

Reputation: 37505

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).

Upvotes: 0

Manfred
Manfred

Reputation: 3142

The ArchUnit, currently in version 0.16.0, does not analyze parameter values for method calls.

The sonar rule "Printf-style format strings should be used correctly" might however catch these bugs.

Upvotes: 2

Related Questions