MDC详解
MDC(Mapped Diagnostic Context,映射调试上下文)是 log4j 、logback及log4j2 提供的一种方便在多线程条件下记录日志的功能。
MDC 可以看成是一个与当前线程绑定的哈希表,可以往其中添加键值对。MDC 中包含的内容可以被同一线程中执行的代码所访问。
当前线程的子线程会继承其父线程中的 MDC 的内容。当需要记录日志时,只需要从 MDC 中获取所需的信息即可。
MDC 的内容则由程序在适当的时候保存进去。对于一个 Web 应用来说,通常是在请求被处理的最开始保存这些数据。
spring boot中使用
1、添加拦截器
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author zh
* @version 1.0
* @date 2021/5/10 22:41
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ContextFilter extends OncePerRequestFilter {
/**
* Same contract as for {@code doFilter}, but guaranteed to be
* just invoked once per request within a single request thread.
* See {@link #shouldNotFilterAsyncDispatch()} for details.
* <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
* default ServletRequest and ServletResponse ones.
*
* @param request
* @param response
* @param filterChain
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
MDC.put(Constants.CLIENT_IP,IPUtil.getIpAddr(request));
if(StringUtils.isNotBlank(request.getHeader("Authorization"))) {
MDC.put(Constants.LOG_TRACE_ID, MD5Utils.md5Encrypt32Lower(request.getHeader("Authorization")));
}
filterChain.doFilter(request, response);
} finally {
MDC.clear();
}
}
}
2、注册拦截器
@Bean
public FilterRegistrationBean requestContextRepositoryFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new ContextFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
3、修改logbak日志输出
--修改日志输出格式,添加%X{traceId},traceId和MDC中的键名称一致
<pattern>%date %-5level ${PID:- } [%-15X{clientIp:-}] [%-32X{traceId:-}] [%thread][%X{tid}] : /*[%logger{50}:%line] %msg*/%n</pattern>
输入结果如下