其他分享
首页 > 其他分享> > Sleuth+logback 设置traceid 及自定义信息

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

作者:互联网

使用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
        }

    }}
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>

 

标签:currentSpan,Sleuth,traceid,chain,自定义,request,response,tracer
来源: https://www.cnblogs.com/youngdeng/p/14554369.html