0

I am using PMD tool in eclipse for reviewing code.I am unable to find a solution for the warning message "There is log block surrounded by if " for the line of code - >log.error("exception "+e); However the same warning message goes away for log.info when i write if(log.isInfoEnabled()) log.info("notification "); How can we fix the issue for log.error? It doesn't accept below code :

if(log.isInfoEnabled())
log.error("exception "+e);

Anybody have come across same issue and found a solution please advice. Thanks

coding_with_sabs
  • 121
  • 1
  • 2
  • 10
  • Why do you check if info is enabled before logging an error? – Slaw Apr 05 '19 at 05:57
  • Well then why does PMD report it as a warning ? – coding_with_sabs Apr 05 '19 at 06:40
  • Probably because the code is atypical. That's why I'm asking for clarification; I could see checking if error is enabled before logging an error, but why check info if you're going to log an error? – Slaw Apr 05 '19 at 06:44
  • Right, but there is no method like log.isErrorEnabled() , so i just tried with log.isInfoEnabled(), How can we solve this? – coding_with_sabs Apr 05 '19 at 06:59
  • What logging framework are you using? From the tags I'd assume (perhaps wrongly) log4j2, which does have a [`Logger.isErrorEnabled()`](https://logging.apache.org/log4j/2.x/log4j-api/apidocs/org/apache/logging/log4j/Logger.html#isErrorEnabled--) method. Also, many logging frameworks provide logging methods that accept a functional interface that supplies the message only if the level is enabled; you could use this if you're trying to avoid the string concatenation when unnecessary. – Slaw Apr 05 '19 at 07:12
  • If you're using log4j (version 1) then take a look at [`isEnabledFor`](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Category.html#isEnabledFor(org.apache.log4j.Priority)). – Slaw Apr 05 '19 at 07:16
  • @Slaw, I am using apache log4j version 1, What is the advantage of using log4j version 2 ? And yeah i see the method isEnabedFor(Priority level) but what should be the priority level value to be set as prameter if i am writing code as below if(log.isEnabledFor(?)) log.error("exception "+e); – coding_with_sabs Apr 05 '19 at 07:28
  • You'd use `isEnabledFor(Level.ERROR)` (note `Level` is a subclass of `Priority`). As for why you'd use log4j2, see https://stackoverflow.com/questions/30019585/log4j2-why-would-you-use-it-over-log4j and https://logging.apache.org/log4j/log4j-2.2/manual/index.html – Slaw Apr 05 '19 at 07:34
  • Hi Slaw, I changed the code to below,But still PMD is warning "There is log block not surrounded by if" `if(log.isEnabledFor(Level.ERROR)){ log.error("Exc "+e); }` Please help how can i get rid of this warning. – coding_with_sabs Apr 08 '19 at 06:42

0 Answers0