背景:分布式系统中,如何快速定位某个用户的请求日志?
使用Sleuth生成的traceid可以跟踪某个请求,但是很多时候我们需要知道traceid 与某个用户的映射关系,方便定位某个用户的日志
方案:
@Component @Order(TraceWebServletAutoConfiguration.TRACING_FILTER_ORDER + 1) public class CustomHttpSpanExtractor extends GenericFilterBean { private final Tracer tracer; CustomHttpSpanExtractor(Tracer tracer) { this.tracer = tracer; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Span currentSpan = this.tracer.currentSpan(); if (currentSpan == null) { chain.doFilter(request, response); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; try { // mdc(httpRequest,currentSpan.context().traceIdString()); MDC.put(MdcConstant.USER_ID,"userid-12345"); } catch (Exception e) { e.printStackTrace(); } try { chain.doFilter(request, response); } finally { MDC.clear();//must be,threadLocal } }}
logback 配置
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}[${applicationName},%X{X-B3-TraceId:-},%X{userId:-}] [%thread] %-5level %logger{50} - %msg%n</pattern>