'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 1:[1]

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.

Solution 2:[2]

If you can't switch to log4j2 for whatever reason or can't use another log provider, then you can copy the org.apache.log4j.helpers.Loader class from log4j1 into your project keeping the original package name (org.apache.log4j.helpers).

Then in the Loader.java inside your project:

  • comment the part of the static block that deals with the java version, here;
  • comment the boolean java1 = true class variable;
  • change the isJava1() method to always return true;
  • locations that reference the java1 variable must call the isJava1() method.

Now MDC works on Log4j1 + Java9+.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2