1. 参考文章:https://segmentfault.com/a/1190000022721682,https://blog.csdn.net/millery22/article/details/86672354
2. 开始使用了TreadLocal和拦截器增加标识,但是发现想中消费mq消息的日志,无法打印唯一标识。文章:https://blog.csdn.net/whxwkb/article/details/111594712。查询到MDC可以。
3. 拦截器:
public class LogInterceptor implements HandlerInterceptor {
public final static String REQUEST_ID = "requestId";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
try{
String uuid = UUID.randomUUID().toString().replace("-", "");
MDC.put(REQUEST_ID, uuid);
} catch (Exception e) {
// 捕捉异常,不可阻断流程,无需做任何处理
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//移除id
MDC.remove(REQUEST_ID);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
拦截器配置:
@Configuration
public class WebInterceptorConfig extends WebMvcConfigurationSupport {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/login")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
}