Skip to content

Commit

Permalink
add MDCCloseable
Browse files Browse the repository at this point in the history
  • Loading branch information
twillouer committed Jul 25, 2014
1 parent fdafef0 commit 5c76844
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
51 changes: 51 additions & 0 deletions slf4j-api/src/main/java/org/slf4j/MDC.java
Expand Up @@ -24,6 +24,8 @@
*/
package org.slf4j;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;

import org.slf4j.helpers.NOPMDCAdapter;
Expand Down Expand Up @@ -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() {
}

Expand Down Expand Up @@ -116,6 +133,40 @@ public static void put(String key, String val)
mdcAdapter.put(key, val);
}

/**
* 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.
Expand Down
10 changes: 10 additions & 0 deletions slf4j-nop/src/test/java/org/slf4j/InvocationTest.java
Expand Up @@ -24,6 +24,8 @@
*/
package org.slf4j;

import java.io.Closeable;
import java.io.IOException;
import junit.framework.TestCase;


Expand Down Expand Up @@ -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();
}
}

0 comments on commit 5c76844

Please sign in to comment.