Wednesday, September 28, 2011

PMD - Java Logging Rules

The twelfth installment of explanation of PMD rules covering Java Logging Rules.

Java Logging Rules

The Java Logging ruleset contains a collection of rules that find questionable usages of the logger.

MoreThanOneLogger

Normally only one logger is used in each class.

Example

class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    // It is very rare to see two loggers on a class, normally
    // log information is multiplexed by levels
    Logger log2= Logger.getLogger(Foo.class.getName());
}

LoggerIsNotStaticFinal

In most cases, the Logger can be declared static and final.

Example

class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    // It is much better to declare the logger as follows 
    // static final Logger log = Logger.getLogger(Foo.class.getName());
}

SystemPrintln

System.(out|err).print is used, consider using a logger.

Example

class Foo{
    Logger log = Logger.getLogger(Foo.class.getName());
    public void testA () {
        System.out.println("Entering test");
        // Better use this
        log.fine("Entering test");
    }
}

AvoidPrintStackTrace

Avoid printStackTrace(); use a logger call instead.

Example

class Foo {
void bar() {
  try {
   // do something
  } catch (Exception e) {
   e.printStackTrace();
  }
}
}

No comments: