Skip to content

Instantly share code, notes, and snippets.

@matthewadams
Created May 19, 2022 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewadams/ba8fff9fd04c3e05aa9b29952a779a0f to your computer and use it in GitHub Desktop.
Save matthewadams/ba8fff9fd04c3e05aa9b29952a779a0f to your computer and use it in GitHub Desktop.
Convenient logback json support using Kotlin extensions
// NOTE: inspired by https://www.innoq.com/en/blog/structured-logging/#structuredarguments
import net.logstash.logback.argument.StructuredArguments.kv
import org.slf4j.Logger
const val DEFAULT_KEY = "ctx"
internal fun o(ctx: Any? = null) = kv(
DEFAULT_KEY,
object {
val `class` = if (ctx == null) "(null)" else ctx::class.java.canonicalName
val `object` = ctx
}
)
fun Logger.traceJson(format: String, ctx: Any? = null) {
this.trace(format, o(ctx))
}
fun Logger.debugJson(format: String, ctx: Any? = null) {
this.debug(format, o(ctx))
}
fun Logger.infoJson(format: String, ctx: Any? = null) {
this.info(format, o(ctx))
}
fun Logger.warnJson(format: String, ctx: Any? = null) {
this.warn(format, o(ctx))
}
fun Logger.errorJson(format: String, ctx: Any? = null) {
this.error(format, o(ctx))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment