Skip to content

Commit ec34bd2

Browse files
SiegfriedTobias1carterkozak
authored andcommitted
LOG4J2-2939: Fix NPE in MDCContextMap (#430)
Accomodate for the fact that MDC.getCopyOfContextMap() may return null
1 parent b417ca7 commit ec34bd2

File tree

2 files changed

+44
-3
lines changed

2 files changed

+44
-3
lines changed

log4j-to-slf4j/src/main/java/org/apache/logging/slf4j/MDCContextMap.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ public void clear() {
7171

7272
@Override
7373
public boolean containsKey(final String key) {
74-
return MDC.getCopyOfContextMap().containsKey(key);
74+
Map<String, String> map = MDC.getCopyOfContextMap();
75+
return map != null && map.containsKey(key);
7576
}
7677

7778
@Override
@@ -88,7 +89,8 @@ public Map<String, String> getImmutableMapOrNull() {
8889

8990
@Override
9091
public boolean isEmpty() {
91-
return MDC.getCopyOfContextMap().isEmpty();
92+
Map<String, String> map = MDC.getCopyOfContextMap();
93+
return map == null || map.isEmpty();
9294
}
9395

9496
@Override

log4j-to-slf4j/src/test/java/org/apache/logging/slf4j/LoggerTest.java

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import org.junit.Before;
3434
import org.junit.ClassRule;
3535
import org.junit.Test;
36+
import org.slf4j.MDC;
3637

3738
import static org.hamcrest.Matchers.*;
3839
import static org.junit.Assert.*;
@@ -183,5 +184,43 @@ public void mdc() {
183184
assertThat(list.strList, hasSize(2));
184185
assertTrue("Incorrect year", list.strList.get(0).startsWith("2010"));
185186
}
186-
}
187187

188+
@Test
189+
public void mdcNullBackedIsEmpty() {
190+
assertNull("Setup wrong", MDC.getCopyOfContextMap());
191+
assertTrue(ThreadContext.isEmpty());
192+
}
193+
194+
@Test
195+
public void mdcNullBackedContainsKey() {
196+
assertNull("Setup wrong", MDC.getCopyOfContextMap());
197+
assertFalse(ThreadContext.containsKey("something"));
198+
}
199+
200+
@Test
201+
public void mdcNullBackedContainsNullKey() {
202+
assertNull("Setup wrong", MDC.getCopyOfContextMap());
203+
assertFalse(ThreadContext.containsKey(null));
204+
}
205+
206+
@Test
207+
public void mdcContainsNullKey() {
208+
try {
209+
ThreadContext.put("some", "thing");
210+
assertNotNull("Setup wrong", MDC.getCopyOfContextMap());
211+
assertFalse(ThreadContext.containsKey(null));
212+
} finally {
213+
ThreadContext.clearMap();
214+
}
215+
}
216+
217+
@Test
218+
public void mdcCannotContainNullKey() {
219+
try {
220+
ThreadContext.put(null, "something");
221+
fail("should throw");
222+
} catch (IllegalArgumentException | NullPointerException e) {
223+
// expected
224+
}
225+
}
226+
}

0 commit comments

Comments
 (0)