pmd / pmd

An extensible multilanguage static code analyzer.
https://pmd.github.io
Other
4.88k stars 1.5k forks source link

[java] False InvalidLogMessageFormat when final parameter is Supplier<Throwable> #3601

Open krallus opened 3 years ago

krallus commented 3 years ago

Affects PMD Version: 7.0.0

Rule: InvalidLogMessageFormat

Description: PMD issues a false positive "InvalidLogMessageFormat" with message "Too many arguments, expected 1 argument but have 2" (for the below code sample). This occurs when the parameters are passed as type Supplier<?> functions and the final supplier supplies a Throwable type. Log4j always treats the last parameter as special when it is a Throwable, even when using parameter suppliers for all parameters. Therefore, in the code sample below, there is indeed only one parameter that is supplied.

Code Sample demonstrating the issue:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Foo {
    private static final Logger logger = LogManager.getLogger();

    public void myMethod(Object id) {
        try {
            throw new Exception("aaa");
        } catch (final Exception exception) {
            logger.warn("Object with ID {} had a problem.", () -> String.valueOf(id), () -> exception);
        }
    }
}

Expected outcome: No problem reported as the last parameter references an exception.

However, PMD reports a violation at the logger.warn(...) line.

Running PMD through: PMD Plug-in 4.29 for Eclipse

krallus commented 1 year ago

Note that I just confirmed that this is still an issue with: PMD Plug-in 7.0.0.v20230502-1028-rc2 Log4j 2.20.0 Eclipse 2023-03 (4.27.0) Linux Mint 21.1 Cinnamon

adangel commented 7 months ago

The issue is still reproducible under PMD 7.0.0.