Skip to content

Commit f29d2a0

Browse files
author
Alphonse Bendt
committed
Kotlin#119: first implementation of a SLF4J MDC Context
1 parent e106815 commit f29d2a0

File tree

3 files changed

+42
-7
lines changed

3 files changed

+42
-7
lines changed

integration/kotlinx-coroutines-slf4j/src/main/kotlin/kotlinx/coroutines/experimental/slf4j/MDCContext.kt

+5-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import kotlin.coroutines.experimental.CoroutineContext
88

99
class MDCContext(
1010
private val context: CoroutineContext,
11-
private val contextMap: Map<String, String> = MDC.getCopyOfContextMap()
11+
private val contextMap: Map<String, String>? = MDC.getCopyOfContextMap()
1212
) : AbstractCoroutineContextElement(ContinuationInterceptor), ContinuationInterceptor {
1313

1414
override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
@@ -25,7 +25,10 @@ class MDCContext(
2525
private inner class Wrapper<T>(private val continuation: Continuation<T>) : Continuation<T> {
2626
private inline fun wrap(block: () -> Unit) {
2727
try {
28-
MDC.setContextMap(contextMap)
28+
contextMap?.let {
29+
MDC.setContextMap(contextMap)
30+
}
31+
2932
block()
3033
} finally {
3134
MDC.clear()

integration/kotlinx-coroutines-slf4j/src/test/kotlin/kotlinx/coroutines/experimental/slf4j/MDCContextTest.kt

+22
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
11
package kotlinx.coroutines.experimental.slf4j
22

33
import kotlinx.coroutines.experimental.*
4+
import org.junit.After
5+
import org.junit.Before
46
import org.junit.Test
57
import org.slf4j.MDC
68
import kotlin.test.assertEquals
9+
import kotlin.test.assertNull
710

811
class MDCContextTest : TestBase() {
912

13+
@Before
14+
fun setUp() {
15+
MDC.clear()
16+
}
17+
18+
@After
19+
fun tearDown() {
20+
MDC.clear()
21+
}
22+
1023
@Test
1124
fun mdcContextIsNotPassedByDefaultBetweenCoRoutines() = runTest {
1225
expect(1)
@@ -60,4 +73,13 @@ class MDCContextTest : TestBase() {
6073
assertEquals(mdcValue, "myValue")
6174
}
6275
}
76+
77+
@Test
78+
fun mdcContextMayBeEmpty() {
79+
runBlocking(MDCContext(DefaultDispatcher)) {
80+
val mdcValue = MDC.get("myKey")
81+
82+
assertNull(mdcValue)
83+
}
84+
}
6385
}
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
1-
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
2-
<layout>
3-
<Pattern>%X{first} %X{last} - %m%n</Pattern>
4-
</layout>
5-
</appender>
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<configuration debug="false">
3+
4+
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
5+
<layout>
6+
<Pattern>%X{first} %X{last} - %m%n</Pattern>
7+
</layout>
8+
</appender>
9+
10+
<root level="DEBUG">
11+
<appender-ref ref="CONSOLE" />
12+
</root>
13+
</configuration>
14+
15+

0 commit comments

Comments
 (0)