FP for InvalidLogMessageFormat when using slf4j-Markers

This commit is contained in:
kris-scheibe
2020-01-25 10:17:59 +01:00
parent d90d5d267c
commit 60cb037f80
2 changed files with 32 additions and 0 deletions

View File

@ -89,6 +89,11 @@ public class InvalidLogMessageFormatRule extends AbstractJavaRule {
final List<ASTExpression> argumentList = parentNode.getFirstChildOfType(ASTPrimarySuffix.class)
.getFirstDescendantOfType(ASTArgumentList.class).findChildrenOfType(ASTExpression.class);
// ignore the first argument if it is a known non-string value, e.g. a slf4j-Marker
if (argumentList.get(0).getType() != null && !argumentList.get(0).getType().equals(String.class)) {
argumentList.remove(0);
}
// remove the message parameter
final ASTExpression messageParam = argumentList.remove(0);
final int expectedArguments = expectedArguments(messageParam);

View File

@ -780,6 +780,33 @@ public class InvalidLogMessageFormatTest {
logger.warn("foo {}", "flibble", "moo", "blah", "blah"); // PMD flags this
logger.warn("foo", "flibble", "moo", "blah", "blah"); // PMD doesn't flag this
}
}
]]></code>
</test-code>
<test-code>
<description>ignore slf4j-Markers when detecting the number of arguments</description>
<expected-problems>2</expected-problems>
<expected-linenumbers>11,17</expected-linenumbers>
<code><![CDATA[
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.helpers.BasicMarkerFactory;
public class InvalidLogMessageFormatTest {
private static final Logger logger = LoggerFactory.getLogger("MyLogger");
private static final Marker marker = BasicMarkerFactory.getMarker("MARKER");
public static void main(String[] args) {
logger.warn(marker, "foo {}", "flibble", "moo", "blah", "blah"); // wrong number of arguments
logger.warn(marker, "foo"); // correct: marker and no arguments
logger.warn(marker, "foo", new Exception()); // correct: marker and one exception parameter
logger.warn(marker, "foo {}", "bar"); // correct: marker and one argument
final var otherMarker = MarkerFactory.getMarker("OTHER_MARKER");
logger.warn(otherMarker, "foo"); // gets flagged as we can't statically determine the type of the "otherMarker" variable
}
}
]]></code>
</test-code>