Skip to content

Commit

Permalink
Support nested putCloseable invocations (issues/404)
Browse files Browse the repository at this point in the history
Signed-off-by: Matthew Pearson <[email protected]>
  • Loading branch information
mdpearson committed Mar 15, 2024
1 parent 448bca1 commit b800deb
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
13 changes: 10 additions & 3 deletions slf4j-api/src/main/java/org/slf4j/MDC.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,19 @@ public class MDC {
*/
public static class MDCCloseable implements Closeable {
private final String key;
private final String previousValue;

private MDCCloseable(String key) {
private MDCCloseable(String key, String previousValue) {
this.key = key;
this.previousValue = previousValue;
}

public void close() {
MDC.remove(this.key);
if (previousValue != null) {
MDC.put(key, previousValue);
} else {
MDC.remove(key);
}
}
}

Expand Down Expand Up @@ -156,8 +162,9 @@ public static void put(String key, String val) throws IllegalArgumentException {
* in case the "key" parameter is null
*/
public static MDCCloseable putCloseable(String key, String val) throws IllegalArgumentException {
String prev = get(key);
put(key, val);
return new MDCCloseable(key);
return new MDCCloseable(key, prev);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,27 @@ public void testCallerInfoWithFluentAPI() {
assertEquals(this.getClass().getName(), event.getLocationInformation().getClassName());
}

@Test
public void testMDCCloseable() {
MDC.MDCCloseable closeable = MDC.putCloseable("k", "v");
assertEquals("v", MDC.get("k"));
closeable.close();
assertNull(MDC.get("k"));
MDC.clear();
}

@Test
public void testMDCCloseablePreExistingKey() {
MDC.put("k", "1");
MDC.MDCCloseable outerCloseable = MDC.putCloseable("k", "2");
assertEquals("2", MDC.get("k"));
MDC.MDCCloseable innerCloseable = MDC.putCloseable("k", "2");
assertEquals("3", MDC.get("k"));
innerCloseable.close();
assertEquals("2", MDC.get("k"));
outerCloseable.close();
assertEquals("1", MDC.get("k"));
MDC.clear();
assertNull(MDC.get("k"));
}
}

0 comments on commit b800deb

Please sign in to comment.