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

Viewed 413

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?

2 Answers

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+.

Related