Skip to content

Commit

Permalink
Support nullables in withLoggingContext
Browse files Browse the repository at this point in the history
`withLoggingContext` now accepts nullable values that won't be written
to the `MDC` (and thus also don't overwrite existing values).
This might be useful if some values are not guaranteed to exist, but you
want them in the `MDC` if possible.

Issue: #172
  • Loading branch information
fdw authored and oshai committed Apr 8, 2021
1 parent bac6142 commit c843f6d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/jvmMain/kotlin/mu/KotlinLoggingMDC.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ import org.slf4j.MDC
* }
* ```
*/
public inline fun <T> withLoggingContext(pair: Pair<String, String>, body: () -> T): T =
MDC.putCloseable(pair.first, pair.second).use { body() }
public inline fun <T> withLoggingContext(pair: Pair<String, String?>, 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:
Expand All @@ -21,12 +25,12 @@ public inline fun <T> withLoggingContext(pair: Pair<String, String>, body: () ->
* }
* ```
*/
public inline fun <T> withLoggingContext(vararg pair: Pair<String, String>, body: () -> T): T {
public inline fun <T> withLoggingContext(vararg pair: Pair<String, String?>, 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) }
}
}

Expand Down
24 changes: 24 additions & 0 deletions src/jvmTest/kotlin/mu/KotlinLoggingMDCTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand All @@ -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"))
Expand Down

0 comments on commit c843f6d

Please sign in to comment.