Bug 47107: Add MDC.clear() method
git-svn-id: https://svn.apache.org/repos/asf/logging/log4j/trunk@823968 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 411834a..101e2ba 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -85,6 +85,7 @@
<action action="fix" issue="47967">log4j.ignoreTCL should apply to the getResource method in addition to the loadClass method of org.apache.log4j.helpers.Loader.</action>
<action action="fix" issue="46539">The QuietWriter class does not live up to its published contract.</action>
<action action="add" issue="46983">More Debug output for log4j auto-configure requested.</action>
+ <action action="add" issue="47107">Add MDC.clear().</action>
</release>
diff --git a/src/main/java/org/apache/log4j/MDC.java b/src/main/java/org/apache/log4j/MDC.java
index 47a2dbf..5d861af 100644
--- a/src/main/java/org/apache/log4j/MDC.java
+++ b/src/main/java/org/apache/log4j/MDC.java
@@ -115,6 +115,16 @@
}
}
+ /**
+ * Remove all values from the MDC.
+ * @since 1.2.16
+ */
+ public static void clear() {
+ if (mdc != null) {
+ mdc.clear0();
+ }
+ }
+
private
void put0(String key, Object o) {
@@ -163,4 +173,15 @@
return (Hashtable) ((ThreadLocalMap)tlm).get();
}
}
+
+ private
+ void clear0() {
+ if(!java1 && tlm != null) {
+ Hashtable ht = (Hashtable) ((ThreadLocalMap)tlm).get();
+ if(ht != null) {
+ ht.clear();
+ }
+ }
+ }
+
}
diff --git a/tests/src/java/org/apache/log4j/PatternLayoutTestCase.java b/tests/src/java/org/apache/log4j/PatternLayoutTestCase.java
index aa9c1fc..3c6f982 100644
--- a/tests/src/java/org/apache/log4j/PatternLayoutTestCase.java
+++ b/tests/src/java/org/apache/log4j/PatternLayoutTestCase.java
@@ -288,6 +288,17 @@
assertTrue(Compare.compare(TEMP, "witness/patternLayout.mdc.1"));
}
+ public void testMDCClear() throws Exception {
+ PropertyConfigurator.configure("input/patternLayout.mdc.1.properties");
+ MDC.put("key1", "va11");
+ MDC.put("key2", "va12");
+ logger.debug("Hello World");
+ MDC.clear();
+ logger.debug("Hello World");
+
+ assertTrue(Compare.compare(TEMP, "witness/patternLayout.mdc.clear"));
+ }
+
void common() {
diff --git a/tests/witness/patternLayout.mdc.clear b/tests/witness/patternLayout.mdc.clear
new file mode 100644
index 0000000..aa71f63
--- /dev/null
+++ b/tests/witness/patternLayout.mdc.clear
@@ -0,0 +1,2 @@
+DEBUG - Hello World {{key1,va11}{key2,va12}}
+DEBUG - Hello World {}
\ No newline at end of file