Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

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.

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

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.