@@ -28,8 +28,47 @@ public typealias MDCContextMap = Map<String, String>?
28
28
* using [MDC.put]. These updates are going to be lost on the next suspension and
29
29
* reinstalled to the MDC context that was captured or explicitly specified in
30
30
* [contextMap] when this object was created on the next resumption.
31
- * Use `withContext(MDCContext()) { ... }` to capture updated map of MDC keys and values
32
- * for the specified block of code.
31
+ *
32
+ * For example, the following code will not work as expected:
33
+ *
34
+ * ```
35
+ * launch(MDCContext()) {
36
+ * MDC.put("key", "value") // This update will be lost
37
+ * delay(100)
38
+ * println(MDC.get("key")) // This will print null
39
+ * }
40
+ * ```
41
+ *
42
+ * Instead, you should use [withContext] to capture the updated MDC context:
43
+ *
44
+ * ```
45
+ * launch(MDCContext()) {
46
+ * MDC.put("key", "value") // This update will be captured
47
+ * withContext(MDCContext()) {
48
+ * delay(100)
49
+ * println(MDC.get("key")) // This will print "value"
50
+ * }
51
+ * }
52
+ * ```
53
+ *
54
+ * There is no way to implicitly propagate MDC context updates from inside the coroutine to the outer scope.
55
+ * You have to capture the updated MDC context and restore it explicitly. For example:
56
+ *
57
+ * ```
58
+ * MDC.put("a", "b")
59
+ * val contextMap = withContext(MDCContext()) {
60
+ * MDC.put("key", "value")
61
+ * withContext(MDCContext()) {
62
+ * MDC.put("key2", "value2")
63
+ * withContext(MDCContext()) {
64
+ * yield()
65
+ * MDC.getCopyOfContextMap()
66
+ * }
67
+ * }
68
+ * }
69
+ * // contextMap contains: {"a"="b", "key"="value", "key2"="value2"}
70
+ * MDC.setContextMap(contextMap)
71
+ * ```
33
72
*
34
73
* @param contextMap the value of [MDC] context map.
35
74
* Default value is the copy of the current thread's context map that is acquired via
0 commit comments