diff --git a/src/jvmMain/kotlin/mu/KotlinLoggingMDC.kt b/src/jvmMain/kotlin/mu/KotlinLoggingMDC.kt index 5cc1c8a9..93691279 100644 --- a/src/jvmMain/kotlin/mu/KotlinLoggingMDC.kt +++ b/src/jvmMain/kotlin/mu/KotlinLoggingMDC.kt @@ -10,8 +10,12 @@ import org.slf4j.MDC * } * ``` */ -public inline fun withLoggingContext(pair: Pair, body: () -> T): T = - MDC.putCloseable(pair.first, pair.second).use { body() } +public inline fun withLoggingContext(pair: Pair, body: () -> T): T = + if (pair.second != null) { + MDC.putCloseable(pair.first, pair.second).use { body() } + } else { + body() + } /** * Use a vary number of pairs in MDC context. Example: @@ -21,12 +25,12 @@ public inline fun withLoggingContext(pair: Pair, body: () -> * } * ``` */ -public inline fun withLoggingContext(vararg pair: Pair, body: () -> T): T { +public inline fun withLoggingContext(vararg pair: Pair, body: () -> T): T { try { - pair.forEach { MDC.put(it.first, it.second) } + pair.filter { it.second != null }.forEach { MDC.put(it.first, it.second) } return body() } finally { - pair.forEach { MDC.remove(it.first) } + pair.filter { it.second != null }.forEach { MDC.remove(it.first) } } } diff --git a/src/jvmTest/kotlin/mu/KotlinLoggingMDCTest.kt b/src/jvmTest/kotlin/mu/KotlinLoggingMDCTest.kt index a3637ccc..ab5dd47b 100644 --- a/src/jvmTest/kotlin/mu/KotlinLoggingMDCTest.kt +++ b/src/jvmTest/kotlin/mu/KotlinLoggingMDCTest.kt @@ -21,6 +21,15 @@ class KotlinLoggingMDCTest { assertNull(MDC.get("a")) } + @Test + fun `simple nullable pair withLoggingContext`() { + assertNull(MDC.get("a")) + withLoggingContext("a" to null) { + assertNull(MDC.get("a")) + } + assertNull(MDC.get("a")) + } + @Test fun `multiple pair withLoggingContext`() { assertNull(MDC.get("a")) @@ -33,6 +42,21 @@ class KotlinLoggingMDCTest { assertNull(MDC.get("c")) } + @Test + fun `multiple nullable pair withLoggingContext`() { + assertNull(MDC.get("a")) + assertNull(MDC.get("c")) + MDC.put("e", "f") + withLoggingContext("a" to "b", "c" to null, "e" to null) { + assertEquals("b", MDC.get("a")) + assertNull(MDC.get("c")) + assertEquals("f", MDC.get("e")) + } + assertNull(MDC.get("a")) + assertNull(MDC.get("c")) + assertEquals("f", MDC.get("e")) + } + @Test fun `map withLoggingContext`() { assertNull(MDC.get("a"))