Skip to content

Instantly share code, notes, and snippets.

@mazzeb
Created July 14, 2020 07:19
Show Gist options
  • Save mazzeb/c20688597c2fb5ef924e864d53b47701 to your computer and use it in GitHub Desktop.
Save mazzeb/c20688597c2fb5ef924e864d53b47701 to your computer and use it in GitHub Desktop.
LoggerDelegate as described at https://www.baeldung.com/kotlin-logging
import org.slf4j.Logger
import org.slf4j.LoggerFactory.getLogger
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlin.reflect.full.companionObject
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
override fun getValue(thisRef: R, property: KProperty<*>): Logger = getLogger(getClassForLogging(thisRef.javaClass))
private inline fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
return javaClass.enclosingClass?.takeIf {
it.kotlin.companionObject?.java == javaClass
} ?: javaClass
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment