Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support nested putCloseable invocations (issues/404) #405

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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", "3");
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"));
}
}