Logging in Kotlin Top Level Functions

Niel de Wet
1 min readOct 25, 2018

--

When you’re declaring a logger in a class or object it is pretty simple to get a logger with the fully qualified name of the class you’re in. You typically do something like:

LogManager.getLogger(this.javaClass)

What if you don’t have access to the all-important this variable? Top level functions are one place where you don’t, but you’d still like your logger to have a name that points to the Kotlin file where the function is declared. A simple way is to use an empty lambda and get its javaClass, and strip all the extra suffixes.

This is how to get a logger based on the javaClass in a Kotlin file (outside of a class or object):

The really nice thing about this approach is that you can also use it in a class, which means you have one approach that works everywhere you need a logger.

--

--

No responses yet