Java 8 automatically injecting logger using trait

‚Äč

This post explains how default methods in Java 8 can be used as a trait to automatically inject logger instances.

To use logging in Java code, we need to add this boiler plate code in every Java class.

private static final Logger logger = Logger.getLogger(MyClass.class.getName());

Like me, most of you would hate copy pasting this line and updating the class name in every Java file. Luckily, Java 8 supports default methods in interfaces which can be used to solve this problem.

Java 8 default methods as traits

Trait is a programming concept used to define a set of behaviors that classes can extend it or override implementation. Trait is similar to Interface, but it can also have a default implementation. Java 8 added default methods in Interfaces which we can use to implement Traits.

For example, we can define a Loggable trait with default implementation like below

public interface Loggable {

    default Logger logger() {
        return Logger.getLogger(this.getClass().getName());
    }
}

Then, any class can use it by simply implementing Loggable interface without duplication of code. Eg.

public class MyClass implements Loggable {
   public void method1() {
        logger().info("on method1");
        ...
    }
}

Any class can also override the default implementation if it needs to be. If a class has to do lot of logging, calling logger() method might add slight performance overhead. So to improve performance, we can cache the value in an instance variable like

private final Logger logger = logger();
comments powered by Disqus

Facebook Comments