Skip to content

Commit 1f438ae

Browse files
committed
Support nested putCloseable invocations (issues/404)
Signed-off-by: Matthew Pearson <[email protected]>
1 parent 448bca1 commit 1f438ae

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

slf4j-api/src/main/java/org/slf4j/MDC.java

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,13 +75,19 @@ public class MDC {
7575
*/
7676
public static class MDCCloseable implements Closeable {
7777
private final String key;
78+
private final String previousValue;
7879

79-
private MDCCloseable(String key) {
80+
private MDCCloseable(String key, String previousValue) {
8081
this.key = key;
82+
this.previousValue = previousValue;
8183
}
8284

8385
public void close() {
84-
MDC.remove(this.key);
86+
if (previousValue != null) {
87+
MDC.put(key, previousValue);
88+
} else {
89+
MDC.remove(key);
90+
}
8591
}
8692
}
8793

@@ -156,8 +162,9 @@ public static void put(String key, String val) throws IllegalArgumentException {
156162
* in case the "key" parameter is null
157163
*/
158164
public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException {
165+
String prev = get(key);
159166
put(key, val);
160-
return new MDCCloseable(key);
167+
return new MDCCloseable(key, prev);
161168
}
162169

163170
/**

slf4j-reload4j/src/test/java/org/slf4j/reload4j/InvocationTest.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,4 +206,27 @@ public void testCallerInfoWithFluentAPI() {
206206
assertEquals(this.getClass().getName(), event.getLocationInformation().getClassName());
207207
}
208208

209+
@Test
210+
public void testMDCCloseable() {
211+
MDC.MDCCloseable closeable = MDC.putCloseable("k", "v");
212+
assertEquals("v", MDC.get("k"));
213+
closeable.close();
214+
assertNull(MDC.get("k"));
215+
MDC.clear();
216+
}
217+
218+
@Test
219+
public void testMDCCloseablePreExistingKey() {
220+
MDC.put("k", "1");
221+
MDC.MDCCloseable outerCloseable = MDC.putCloseable("k", "2");
222+
assertEquals("2", MDC.get("k"));
223+
MDC.MDCCloseable innerCloseable = MDC.putCloseable("k", "3");
224+
assertEquals("3", MDC.get("k"));
225+
innerCloseable.close();
226+
assertEquals("2", MDC.get("k"));
227+
outerCloseable.close();
228+
assertEquals("1", MDC.get("k"));
229+
MDC.clear();
230+
assertNull(MDC.get("k"));
231+
}
209232
}

0 commit comments

Comments
 (0)