Search code examples
javalog4jmdc

Why log4j stop running MDC logic if Java version is 11, 11.1x, etc


I use MDC for helping log4j loging more information. Everything works well until I updated java version to 11. This is my log4j config (pseodo code)

log4j.appender.R.layout.ConversionPattern = [%-4p] %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%X{request-id}] %l %m%n

This what I did for MDC

MDC.put("request-id","example-request-id")

By expectation, there should be request-id being logged. However it doesn't work if Java version is 11.

Following is my findings from log4j code.

There is a code in "org.apache.log4j.helpers.Loader" to set java1,

    String prop = OptionConverter.getSystemProperty("java.version", null);
    
    if(prop != null) {
      int i = prop.indexOf('.');
      if(i != -1) { 
        if(prop.charAt(i+1) != '1')
        java1 = false;
      } 
    }

And then, some code in "org.apache.log4j.MDC#MDC" to stop logic.

void put0(String key, Object o) {
    if(java1 || tlm == null) {
      return;
    }
...
}

In summary, the MDC wouldn't work if the java version were 11,12,13,..., 11.1x, 12.1x,..., ect. Isn't this look like a bug?


Solution

  • This is a bug. However, Log4j is marked as end-of-life since August 5, 2015 (http://logging.apache.org/log4j/1.2/) and

    Users of Log4j 1 are recommended to upgrade to Apache Log4j 2

    Specifically the problem with MDC and Java 9 is well known: Log4j 1.2 is broken on Java 9, but it is unlikely that anyone will fix this ever.