Skip to content
RadBuilds RadBuilds
java kotlin logging slf4j

Logging in Kotlin

How to declare loggers idiomatically in Kotlin using companion objects and a SLF4J wrapper library.

Radosław Domański

Radosław Domański

2 min read

Hello There!
I’ve been pretty busy lately. Partially, because I’m learning Kotlin in my spare time.
I started rewriting one of my coding challenges (maybe I’ll write something about it later on. for now you may want to check this repository out) and one of my problems was…
how to instantiate loggers properly?
This may seem stupid, but Kotlin rejects the idea of static fields, so you can’t really write

    private static final Logger LOG = LoggerFactory.getLogger(SomeClass.class);

in Kotlin. On the other hand you can use companion objects:

    companion object {
        private val LOG = LoggerFactory.getLogger(TradeValidationEndpoint::class.java)
    }

But it’s not that pretty, right?
Especially given the fact that Kotlin tries to be as expressive as possible.

If you search for a second you’ll find some information about that:

and plenty more.
And all that is great, but… A more general approach would be nice.

Well… Lucky us! oshai already created a library wrapping SLF4J

And it’s great! But I really enjoyed using SLF4J-ext methods (entry and exit) and I feel like LOG is a better name for a static logger than logger
So I made my own version of this library :) You can find it here

This is how you can declare a logger in Kotlin now:
    companion object : KLogging()

and use it like that:

    LOG.entry(input)
    
    return LOG.exit(output)

hopefully you’ll like it. I have to think about sending those changes to the guy.
Maybe his project will benefit from them? :)

cheers!

Back to Blog
Share:

Follow along

Stay in the loop — new articles, thoughts, and updates.