Tipp: Logging Shortcuts

Category: 

Logging Frameworks like Log4J are very important tools, but sometimes one have to write the same code multiple times, just to give a Logger to each class. But thanks to Java 8, we can solve this problem.

The Problem

For each class we have to write nearly the same line and afterwards we always have to type logger.debug(...). The later one is a bit odd, but not the big problem. The declaration of each Logger is what we want to remove.
public class A {
  private static Logger logger = Logger.getLogger(A.class);

  public void methodA() {
    logger.debug("Debug message");
  }
  // ...
}
public class B {
  private static Logger logger = Logger.getLogger(B.class);

  public void methodB() {
    logger.debug("Debug message");
  }
  // ...
}

Java 8 Rescue

Thanks to Java 8 and it's default methods for interfaces. We can now write a Loggable interface, which gives each implementing class the correct Logger.
Furthermore we can reduce our code for calls to frequently used methods.

public interface Loggable {
  public default Logger getLogger() {
    return Logger.getLogger(getClass());
  }

  public default void debug(Object msg) {
    getLogger().debug(msg);
  }

  public default void debug(Object msg, Throwable throwable) {
    getLogger().debug(msg, throwable);
  }
}

Now we let our classes A and B implement the interface and we can call debug(...) directly:

public class A implements Loggable {
  public void methodA() {
    debug("Debug message");
  }
  // ...
}