Create Logger on Package Level Without Class

Viewed 1787

I have a kotlin file with a couple of package-level functions and without any class. I would like to add logging to this class but struggle to find an elegant way to give the logger an identifier.

This is an example

package com.example.myproject.my_package

import org.slf4j.LoggerFactory


private val log = LoggerFactory.getLogger("com.example.myproject.my_package")

fun bla(term: String) {
   log.info("invoked with $term")
}

There are very good best practices to use classes to find a good identifier: link 1 link 2. What's the approach if there are no classes?

I would like to avoid writing the identifier by hand and adjust it when the package name changes. Is there a way to get the package name in kotlin?

2 Answers

You can create a top-level logger for the generated class like this:

private val logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass())

Or for the package like this:

private val logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass().`package`.name)

This has the benefit of not creating an additional class file but it requires atleast Java 7. I have created a library which assists with this and more at https://github.com/kxtra/kxtra-slf4j.

Related