Skip to content

Commit 4c5418b

Browse files
author
oshai
committed
issue #31 - Add MDC support: withLoggingContext
1 parent 4609e59 commit 4c5418b

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package mu
2+
3+
import org.slf4j.MDC
4+
5+
inline fun <T> withLoggingContext(pair: Pair<String, String>, body: () -> T): T =
6+
MDC.putCloseable(pair.first, pair.second).use { body() }
7+
8+
inline fun <T> withLoggingContext(vararg pair: Pair<String, String>, body: () -> T): T {
9+
try {
10+
pair.forEach { MDC.put(it.first, it.second) }
11+
return body()
12+
} finally {
13+
pair.forEach { MDC.remove(it.first) }
14+
}
15+
}
16+
17+
inline fun <T> withLoggingContext(map: Map<String, String>, body: () -> T): T {
18+
try {
19+
map.forEach { MDC.put(it.key, it.value) }
20+
return body()
21+
} finally {
22+
map.forEach { MDC.remove(it.key) }
23+
}
24+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package mu
2+
3+
import org.junit.Assert.*
4+
import org.junit.Test
5+
import org.slf4j.MDC
6+
7+
class KotlinLoggingMDCTest {
8+
9+
@Test
10+
fun `simple pair withLoggingContext`() {
11+
assertNull(MDC.get("a"))
12+
withLoggingContext("a" to "b") {
13+
assertEquals("b", MDC.get("a"))
14+
}
15+
assertNull(MDC.get("a"))
16+
}
17+
18+
@Test
19+
fun `multiple pair withLoggingContext`() {
20+
assertNull(MDC.get("a"))
21+
assertNull(MDC.get("c"))
22+
withLoggingContext("a" to "b", "c" to "d") {
23+
assertEquals("b", MDC.get("a"))
24+
assertEquals("d", MDC.get("c"))
25+
}
26+
assertNull(MDC.get("a"))
27+
assertNull(MDC.get("c"))
28+
}
29+
30+
@Test
31+
fun `map withLoggingContext`() {
32+
assertNull(MDC.get("a"))
33+
assertNull(MDC.get("c"))
34+
withLoggingContext(mapOf("a" to "b", "c" to "d")) {
35+
assertEquals("b", MDC.get("a"))
36+
assertEquals("d", MDC.get("c"))
37+
}
38+
assertNull(MDC.get("a"))
39+
assertNull(MDC.get("c"))
40+
}
41+
}

0 commit comments

Comments
 (0)