diff --git a/slf4j-api/src/main/java/org/slf4j/MDC.java b/slf4j-api/src/main/java/org/slf4j/MDC.java index 8b23cfa70..498cc641a 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 @@ public class MDC { 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() { } @@ -116,6 +133,40 @@ public static void put(String key, String val) mdcAdapter.put(key, val); } + /** + * Put a diagnostic context value (the val parameter) as identified with the + * key parameter into the current thread's diagnostic context map. The + * key parameter cannot be null. The val parameter + * can be null only if the underlying implementation supports it. + * + *

+ * This method delegates all work to the MDC of the underlying logging system. + *

+ * This method return a Closeable object who can remove key when + * close is called. + * + *

+ * Useful with Java 7 for example : + * + * try(Closeable closeable = MDC.putCloseable(key, value)) { + * .... + * } + * + * + * @param key non-null key + * @param val value to put in the map + * @return a Closeable who can remove key when close + * 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 key parameter. The * key 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 cbcfa3d1b..2bfae5a51 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 @@ public void testMDC() { 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(); + } }