Sleuth+logback 设置traceid 及自定义信息

使用Sleuth生成的traceid可以跟踪某个请求,但是很多时候我们需要知道traceid 与某个用户的映射关系,方便定位某个用户的日志

方案:

Sleuth+logback 设置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
        }

    }}
View Code

logback 配置

<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}[${applicationName},%X{X-B3-TraceId:-},%X{userId:-}] [%thread] %-5level %logger{50} - %msg%n</pattern>

Sleuth+logback 设置traceid 及自定义信息

 

上一篇:别再乱打日志了,这样才是定位 bug 打日志的方式!


下一篇:微服务分布式架构中,如何实现日志链路跟踪? (转发)