javalog4jslf4jmdc

slf4j always use NOPMDCAdapter


I use slf4j for logging in my project. And i want to use MDC for logging user ID parameters. So i check tutorials and doc, and make code like:

MDC.put("key", userId)

userId actually is a string.

And i use my usual log4j xml with properties like appenders etc. Add there %X{key} but nothing happen. I simply don't see anything in place of %X{key} but other parameters like %-5p or %c works well.

So i used debug to watch what happen in MDC.put() method, and find out that in initialization of MDC used:

MDCAdapter mdcAdapter;
mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA();

Debug in IDEA shows that it have "Log4jMDCAdapter" like one of implementation for MDCAdapter. But then i look at StaticMDCBinder, and there are code like:

public MDCAdapter getMDCA() {
   return new NOPMDCAdapter();
}

So how it possible that slf4j can initialize MDC with proper adapter for example log4j ??? I didnt get it. Because it always use NOPMDCAdapter it cant store anything in MDC, and cant show it in logging. How i can fix it??

In classpath i have:


Solution

  • Problem solved. It was transcendent dependency from other libraries which used in project. Namely slf4j-jcl, i add part into maven pom, and now it works fine.