withContext
Returns a logger that attaches ctx to every event it emits.
The context travels with the logger object, so unlike ambient propagation (withLogContext from logger-coroutines) it is correct on every platform and under any dispatcher, including multi-threaded ones on Kotlin/Native.
suspend fun handle(requestId: String) {
val log = LoggerFactory.get("Api")
.withContext(LogContext(mapOf("requestId" to requestId)))
log.info { "Starting" } // carries requestId
withContext(Dispatchers.Default) {
log.debug { "Working" } // still carries requestId - it is a field
}
}Content copied to clipboard
Bound values win over ambient context on key collision, and repeated calls merge with later values winning. This logger is not modified.
Return
Parameters
ctx
The context to attach to every event emitted by the returned logger.
Convenience overload of withContext for building a context inline.
val log = LoggerFactory.get("Api").withContext("requestId" to id, "userId" to 42)Content copied to clipboard