bash
配置好log4j2
<PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss}] [%X{TraceId}] [%p] - %l - %m%n"/>
WebMvcConfigurer
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getSecurityInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/swagger-resources/**")
.excludePathPatterns("/webjars/**")
.excludePathPatterns("**/swagger-ui.html");
registry.addInterceptor(new AsyncHandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
response.setHeader("TraceId",TraceIdUtil.get());
TraceIdUtil.putIfAbsent();//生成trace id放入MDC中
return AsyncHandlerInterceptor.super.preHandle(request, response, handler);
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex) throws Exception {
TraceIdUtil.remove();//移除MDC中的trace id
AsyncHandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
});
WebMvcConfigurer.super.addInterceptors(registry);
}
TraceIdUtil
public class TraceIdUtil {
private static final String TRACE_ID_KEY = "TraceId";
private TraceIdUtil() {
}
public static void putIfAbsent() {
if (StringUtils.isBlank(get())) {
put(UUID.randomUUID().toString());
}
}
public static void remove() {
if (get() != null) {
MDC.remove(TRACE_ID_KEY);
}
}
public static String get() {
return MDC.get(TRACE_ID_KEY);
}
public static void put(String traceId) {
MDC.put(TRACE_ID_KEY, traceId);
}
}