Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • 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
like image 445
Wizzard Avatar asked Nov 12 '22 13:11

Wizzard


1 Answers

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.

like image 134
malware Avatar answered Nov 15 '22 05:11

malware