From 2185bf4662b101edfbdb488d109dab8ed579a8ba Mon Sep 17 00:00:00 2001 From: Yury Gribkov Date: Thu, 20 Mar 2025 14:52:24 -0700 Subject: [PATCH] Fix NPE in getMdcCopy of LoggingEventInstrumentation --- .../log4j1/LoggingEventInstrumentation.java | 4 ++++ .../log4j1/src/test/groovy/MdcTest.groovy | 14 +++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/dd-java-agent/instrumentation/log4j1/src/main/java/datadog/trace/instrumentation/log4j1/LoggingEventInstrumentation.java b/dd-java-agent/instrumentation/log4j1/src/main/java/datadog/trace/instrumentation/log4j1/LoggingEventInstrumentation.java index 134c065ef26..bb9607d2bb2 100644 --- a/dd-java-agent/instrumentation/log4j1/src/main/java/datadog/trace/instrumentation/log4j1/LoggingEventInstrumentation.java +++ b/dd-java-agent/instrumentation/log4j1/src/main/java/datadog/trace/instrumentation/log4j1/LoggingEventInstrumentation.java @@ -134,6 +134,10 @@ public static void onExit( if (!injectionRequired) { return; } + if (mdc == null) { + // this.mdcCopy can be null when MDC.getContext() returns null + return; + } // at this point the mdc has been shallow copied. No need to replace with a new hashtable. // Just add our info String serviceName = Config.get().getServiceName(); diff --git a/dd-java-agent/instrumentation/log4j1/src/test/groovy/MdcTest.groovy b/dd-java-agent/instrumentation/log4j1/src/test/groovy/MdcTest.groovy index c89eef110b8..f457cf5bb3f 100644 --- a/dd-java-agent/instrumentation/log4j1/src/test/groovy/MdcTest.groovy +++ b/dd-java-agent/instrumentation/log4j1/src/test/groovy/MdcTest.groovy @@ -16,8 +16,16 @@ class MdcTest extends AgentTestRunner { then: assert event.getMDC("data") == "dog" where: - injectionEnabled | _ - "true" | _ - "false" | _ + injectionEnabled << ["true", "false"] + } + + def "should prevent NPE when MDC context doesn't exist and getMDCCopy"() { + setup: + injectSysConfig("logs.injection", "true") + def event = new LoggingEvent("test", Category.getRoot(), Priority.INFO, "hello world", null) + when: + event.getMDCCopy() + then: + noExceptionThrown() } }