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?
This line should do the job:
private val log = LoggerFactory.getLogger(object{}::class.java.`package`.name)
The object is doing nothing but nevertheless kotlin will create a class to hold the code. You can then access the class, the package, the package name.
Note the usage of backtick because package is a reserved keyword. In java it is not a problem because the real method is getPackage(). The shorter syntax of kotlin transform this method call by a direct access to the property which name now collides with reserved keywords.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With