MDC and slf4jMDC in slf4j
What is MDC in slf4j?
In addition to the trace, debug, info, warn, and error log interfaces, slf4j can also work with MDC to write data to logs. In other words, MDC is used to record logs, but its usage is different from that of log interfaces.
We generally do this when using the log interface.
Logger LOG = LoggerFactory.getLogger("LOGNAME_OR_CLASS");if(LOG.isDebugEnabled()) { LOG.debug("log debug");}
MDC is somewhat different in usage. My understanding is that MDC can manage the data in a processing thread that you want to embody in the log file in a unified manner, determine whether to output logs based on your log file configuration.
For example, MDC can be used in the following scenarios, but not limited:
Use of MDC
Org. slf4j. mdc I personally use tools such as AOP, Filter, or Interceptor to obtain the variables you want to output to the log and call MDC. put (String key, String val), for example, the following code snippet contains row 5th:
@ Around (value = "execution (* com. xx. xx. facade. impl. *. *(..)) ", argNames =" pjp ") public Object validator (ProceedingJoinPoint pjp) throws Throwable {try {String traceId = TraceUtils. begin (); MDC. put ("mdc_trace_id", traceId); Object obj = pjp. proceed (args); return obj;} catch (Throwable e) {// TODO processing error} finally {TraceUtils. endTrace ();}}
The Code records the traceIdm of each request through AOP and uses the variable "mdc_trace_id" to record it. In the log configuration file, you must set the variable to output "mdc_trace_id" to the log file. Take the logback configuration file as an example. Check log 10th rows % X {mdc_trace_id }:
<appender name="ALL" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${CATALINA_BASE}/logs/all.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>${CATALINA_BASE}/logs/all.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy> <encoder charset="UTF-8"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - traceId:[%X{mdc_trace_id}] - %msg%n</pattern> </encoder> </appender>
Benefits of MDC