Question

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:

  • log4j-1.2.16.jar
  • slf4j-api-1.6.1.jar
  • slf4j-api-1.6.2.jar
  • slf4j-jcl-1.6.2.jar
  • slf4j-log4j12-1.6.2.jar
Was it helpful?

Solution 2

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.

OTHER TIPS

SLF4J's MDC is just a facade to switch over the applicable implementation of MDC based on the underlying logger. If it doesn't find any appropriate MDCAdapter from the logger it fallsback to NO-OP adapter. For this it tries to find class named StaticMDCBinder https://github.com/qos-ch/slf4j/blob/v_1.7.25/slf4j-api/src/main/java/org/slf4j/MDC.java#L99

So in this case as mentioned in @Wizzard's answer if there are two StaticMDCBinder classes in your class path tomcat will pick one of it.

slf4j-simple does have a StaticMDCBinder which defaults to NO-OP adapter so removing slf4j-simple jar should solve the issue here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top