Uploaded image for project: 'Log4j 2'
  1. Log4j 2
  2. LOG4J2-2939

NPE in MDCContextMap

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Resolved
    • Major
    • Resolution: Fixed
    • 2.13.3
    • 2.14.0
    • SLF4J Bridge
    • None
    • Empty fresh Spring Boot project on Windows 10 64Bit Oracle JDK11

    Description

      When using the SLF4J adapter and you call ThreadContext.containsKey() before putting anything into the ThreadContext, a NullPointerException is thrown:

      Exception in thread "main" java.lang.NullPointerException
      at org.apache.logging.slf4j.MDCContextMap.containsKey(MDCContextMap.java:74)
      at org.apache.logging.log4j.ThreadContext.containsKey(ThreadContext.java:350)
      at de.semvox.logtest.LogtestApplication.main(LogtestApplication.java:15)

      This is not surprising, as the implementation looks like this

      @Override
      public boolean containsKey(final String key) {
          return MDC.getCopyOfContextMap().containsKey(key);
      }
      

      And the Javadoc for getCopyOfContextMap explicitly states “May be null.”

      This bug is also present in the isEmpty method of the same class.

       

      Workaround: Before any tests are made, e.g. top of main, execute the following

      ThreadContext.put("foo", "bar");
      ThreadContext.remove("foo");

       

      I will create a pull request shortly.

      UPDATE: Here is the pull request: https://github.com/apache/logging-log4j2/pull/430

      Attachments

        Activity

          People

            Unassigned Unassigned
            constantinhirschsemvox Constantin Hirsch
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: