DEV Community

Zakhi
Zakhi

Posted on

Logging in Kotlin made easy

If you have been logging using slf4j in Java, you probably used this idiom a lot:

public class Worker {
    private static final Logger logger = LoggerFactory.getLogger(Worker.class);

    public void work() {
        logger.info("Starting to work!");
    }
}
Enter fullscreen mode Exit fullscreen mode

When you use Kotlin, that long private static final... line? It's no longer necessary with this clever code:

inline val <reified T> T.logger: Logger get() =
    LoggerFactory.getLogger(T::class.java)
Enter fullscreen mode Exit fullscreen mode

Now, our Worker class can be simply written like this:

class Worker {
    fun work() {
        logger.info("Starting to work!")
    }
}
Enter fullscreen mode Exit fullscreen mode

What is going on here?

You might be familiar with inline functions, but calculated properties can be inlined as well.

The compiler replaces each reference to the logger property with the body of its getter expression. The T type parameter refers to the type in the context in which the logger property is used. Since T is reified, it is replaced with the actual type (in our case, Worker) during compilation. So the compiler changes the work() method body to:

LoggerFactory.getLogger(Worker::class.java).info("Starting to work!")
Enter fullscreen mode Exit fullscreen mode

Since T can be any type, you can use the logger property in any class without the need to declare and assign it. This is a nice pattern to eliminate repeatable code.

Top comments (0)