add MDCCloseable
diff --git a/slf4j-api/src/main/java/org/slf4j/MDC.java b/slf4j-api/src/main/java/org/slf4j/MDC.java
index 8b23cfa..498cc64 100644
--- a/slf4j-api/src/main/java/org/slf4j/MDC.java
+++ b/slf4j-api/src/main/java/org/slf4j/MDC.java
@@ -24,6 +24,8 @@
*/
package org.slf4j;
+import java.io.Closeable;
+import java.io.IOException;
import java.util.Map;
import org.slf4j.helpers.NOPMDCAdapter;
@@ -66,6 +68,21 @@
static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder";
static MDCAdapter mdcAdapter;
+ /**
+ * An adapter to remove the key when done.
+ */
+ private static class MDCCloseable implements Closeable {
+ private final String key;
+
+ private MDCCloseable(String key) {
+ this.key = key;
+ }
+
+ public void close() {
+ MDC.remove(this.key);
+ }
+ }
+
private MDC() {
}
@@ -117,6 +134,40 @@
}
/**
+ * Put a diagnostic context value (the <code>val</code> parameter) as identified with the
+ * <code>key</code> parameter into the current thread's diagnostic context map. The
+ * <code>key</code> parameter cannot be null. The <code>val</code> parameter
+ * can be null only if the underlying implementation supports it.
+ *
+ * <p>
+ * This method delegates all work to the MDC of the underlying logging system.
+ * <p>
+ * This method return a <code>Closeable</code> object who can remove <code>key</code> when
+ * <code>close</code> is called.
+ *
+ * <p>
+ * Useful with Java 7 for example :
+ * <code>
+ * try(Closeable closeable = MDC.putCloseable(key, value)) {
+ * ....
+ * }
+ * </code>
+ *
+ * @param key non-null key
+ * @param val value to put in the map
+ * @return a <code>Closeable</code> who can remove <code>key</code> when <code>close</code>
+ * is called.
+ *
+ * @throws IllegalArgumentException
+ * in case the "key" parameter is null
+ */
+ public static Closeable putCloseable(String key, String val)
+ throws IllegalArgumentException {
+ put(key, val);
+ return new MDCCloseable(key);
+ }
+
+ /**
* Get the diagnostic context identified by the <code>key</code> parameter. The
* <code>key</code> parameter cannot be null.
*
diff --git a/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java
index cbcfa3d..2bfae5a 100644
--- a/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java
+++ b/slf4j-nop/src/test/java/org/slf4j/InvocationTest.java
@@ -24,6 +24,8 @@
*/
package org.slf4j;
+import java.io.Closeable;
+import java.io.IOException;
import junit.framework.TestCase;
@@ -117,4 +119,12 @@
assertNull(MDC.get("k"));
MDC.clear();
}
+
+ public void testMDCCloseable() throws IOException {
+ Closeable closeable = MDC.putCloseable("k", "v");
+ assertNull(MDC.get("k"));
+ closeable.close();
+ assertNull(MDC.get("k"));
+ MDC.clear();
+ }
}