Skip to content

[java] GuardLogStatement: False positive when guard is not a direct parent #4282

Closed

Description

@Frettman

Affects PMD Version:
6.53.0+
7.0.0

Rule: GuardLogStatement

Description:

I have an additional if between the guard method and the actual call to a log method (see example below). In the else I'm directly calling a (simple getter) method to provide an argument to the log method, which triggers the need for a guard. This raises a violation: Logger calls should be surrounded by log level guards.
The rule does not recognize that there's a guard around it, just not as direct parent in the syntax tree.

Code Sample demonstrating the issue:

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

public class Foo {
    private static final Logger LOG = LogManager.getLogger(Foo.class);
    public void test(String arg1) {
        if (LOG.isWarnEnabled()) {
          if (someCondition) {
            String msg = "Message 1 with one argument: ";
            LOG.warn(msg + arg1);
          } else {
            String msg = "Message 2 with two arguments: {}, {}.";
            LOG.warn(msg + arg1);
          }
        }
    }
}

Expected outcome:

PMD should look further around it to detect a guard method.

Running PMD through: Maven | Eclipse Plug-in

Activity

  1. added
    a:false-positive
    on Jan 5, 2023
  2. changed the title [-][java] GuardLogStatement only detects guard methods immediately around it.[/-] [+][java] GuardLogStatement only detects guard methods immediately around it[/+] on Jan 19, 2023
  3. added
    needs:pmd7-revalidation
    on Mar 17, 2024
  4. removed
    needs:pmd7-revalidation
    on Mar 25, 2024
  5. SheikhJebran-Philips commented on Jul 9, 2024

    @SheikhJebran-Philips

    facing the same issue

  6. krallus commented on Oct 3, 2024

    @krallus

    Interestingly, this issue does not occur for me in PMD 7.2, 7.3, or 7.4. However, it is a problem in PMD versions 7.5 and 7.6.

  7. added this to the 7.20.0 milestone on Dec 21, 2025
  8. changed the title [-][java] GuardLogStatement only detects guard methods immediately around it[/-] [+][java] GuardLogStatement: False positive when guard is not a direct parent[/+] on Dec 21, 2025
  9. added a commit that references this issue on Dec 21, 2025
  10. added a commit that references this issue on Dec 21, 2025
    d1bc5dd
  11. added a commit that references this issue on Feb 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions