MDC日志跟踪
MDC是log4j,logback和java.util.logging中提供的一种方便在多线程下记录日志的功能,全称是Mapped Diagnostic Context,可以看做是一个与当前线程绑定的哈希表,依赖于ThreadLocalMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class LogInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String traceId = request.getHeader("traceId"); if (traceId == null) { traceId = TraceIdUtil.getTraceId(); }
MDC.put("traceId", traceId); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { MDC.remove("traceId"); } }
|
在配置日志格式时,使用%X{}来获取MDC中的值
1
| <PatternLayout charset="UTF-8" pattern="[%-5p %d{yyyy-MM-dd HH:mm:ss.SSS} [%X{traceId}]] %l [%m]%n"/>
|
如果想要子线程获取到父线程的MDC内容,在父线程新建子线程之前调用MDC.getCopyOfContextMap()方法将MDC内容取出来传给子线程,子线程在执行操作前先调用MDC.setContextMap()方法将父线程的MDC内容设置到子线程