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 } }}
logback 配置
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}[${applicationName},%X{X-B3-TraceId:-},%X{userId:-}] [%thread] %-5level %logger{50} - %msg%n</pattern>
所有内容皆为个人总结或转载别人的文章,只为学习技术。 若您觉得文章有用,欢迎点赞分享! 若无意对您的文章造成侵权,请您留言,博主看到后会及时处理,谢谢。