Skip to content

Instantly share code, notes, and snippets.

@quentinproust
Created January 22, 2020 14:58
Show Gist options
  • Save quentinproust/d75a1203207211497d40ac745d2041d0 to your computer and use it in GitHub Desktop.
Save quentinproust/d75a1203207211497d40ac745d2041d0 to your computer and use it in GitHub Desktop.
Kotlin - Slf4j Logger Extensions
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.lang.Exception
inline fun <reified T> T.logger(): Logger = LoggerFactory.getLogger(T::class.java)
fun Logger.traceWithContext(format: String, vararg contextParams: Pair<String, Any>, exception: Exception? = null) {
val paramsFormat = contextParams.joinToString(",") { "${it.first}={}" }
val paramsArgs = contextParams.map { it.second }.let {
when (exception) {
null -> it
else -> it.plus(exception)
}
}.toTypedArray()
trace("$format -- $paramsFormat", *paramsArgs)
}
fun Logger.debugWithContext(format: String, vararg contextParams: Pair<String, Any>, exception: Exception? = null) {
val paramsFormat = contextParams.joinToString(",") { "${it.first}={}" }
val paramsArgs = contextParams.map { it.second }.let {
when (exception) {
null -> it
else -> it.plus(exception)
}
}.toTypedArray()
debug("$format -- $paramsFormat", *paramsArgs)
}
fun Logger.infoWithContext(format: String, vararg contextParams: Pair<String, Any>, exception: Exception? = null) {
val paramsFormat = contextParams.joinToString(",") { "${it.first}={}" }
val paramsArgs = contextParams.map { it.second }.let {
when (exception) {
null -> it
else -> it.plus(exception)
}
}.toTypedArray()
info("$format -- $paramsFormat", *paramsArgs)
}
inline fun <reified T> T.logInfo(format: String, vararg contextParams: Pair<String, Any>, exception: Exception? = null) {
val paramsFormat = contextParams.joinToString(",") { "${it.first}={}" }
val paramsArgs = contextParams.map { it.second }.let {
when (exception) {
null -> it
else -> it.plus(exception)
}
}.toTypedArray()
LoggerFactory.getLogger(T::class.java).info("$format -- $paramsFormat", *paramsArgs)
}
inline fun <reified T> T.logWarn(format: String, vararg contextParams: Pair<String, Any>, exception: Exception? = null) {
logMeUp(LoggerFactory.getLogger(T::class.java), format, *contextParams, exception = exception) { logger, msg, args ->
logger.warn(msg, *args)
}
}
fun logMeUp(logger: Logger, format: String, vararg contextParams: Pair<String, Any>, exception: Exception? = null, logMethod: (Logger, String, Array<Any>) -> Unit) {
val paramsFormat = contextParams.joinToString(",") { "${it.first}={}" }
val paramsArgs = contextParams.map { it.second }.let {
when (exception) {
null -> it
else -> it.plus(exception)
}
}.toTypedArray()
logMethod.invoke(logger, "$format -- $paramsFormat", paramsArgs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment