Last active
February 22, 2024 11:28
-
-
Save OndraZizka/a7381b8cd86f734bc3b6bf9e528a01ad to your computer and use it in GitHub Desktop.
Kotlin SLF4J log message lazy evaluation based on log level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Lazy evaluation of the messages sent to Slf4j. | |
Usage: | |
log.trace { "State dump: " + expensiveLongSerialisation(state) } | |
See also https://jira.qos.ch/browse/SLF4J-371 | |
*/ | |
import org.slf4j.Logger | |
import org.slf4j.LoggerFactory | |
import kotlin.reflect.KClass | |
import kotlin.reflect.full.companionObject | |
inline fun Logger.error(msg: () -> String) { if (this.isErrorEnabled) this.error(msg()) } | |
inline fun Logger.error(ex: Exception, msg: () -> String) { if (this.isErrorEnabled) this.error(msg(), ex) } | |
inline fun Logger.warn(msg: () -> String) { if (this.isWarnEnabled) this.warn(msg()) } | |
inline fun Logger.warn(ex: Exception, msg: () -> String) { if (this.isWarnEnabled) this.warn(msg(), ex) } | |
inline fun Logger.info(msg: () -> String) { if (this.isInfoEnabled) this.info(msg()) } | |
inline fun Logger.debug(msg: () -> String) { if (this.isDebugEnabled) this.debug(msg()) } | |
inline fun Logger.trace(msg: () -> String) { if (this.isTraceEnabled) this.trace(msg()) } | |
object Logging { | |
inline fun <reified R : Any> R.logger(): Lazy<Logger> = lazy { LoggerFactory.getLogger(unwrapCompanionClass(this.javaClass).name) } | |
} | |
/** Unwraps the companion class to enclosing class given a Java Class. */ | |
fun <T : Any> unwrapCompanionClass(ofClass: Class<T>): Class<*> { | |
return ofClass.enclosingClass?.takeIf { | |
ofClass.enclosingClass.kotlin.companionObject?.java == ofClass | |
} ?: ofClass | |
} | |
/** Unwraps the companion class to enclosing class given a Kotlin Class. */ | |
private fun <T: Any> unwrapCompanionClass(ofClass: KClass<T>): KClass<*> { | |
return unwrapCompanionClass(ofClass.java).kotlin | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment