slf4j 日志增加traceId

阅读更多

 

1.创建Filter

public class TraceIdFilter implements Filter {
    private final String traceIdName="traceId";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String traceId = UUID.randomUUID().toString().replace("-", "");
        MDC.put(traceIdName, traceId);
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove(traceIdName);
        }
    }
}

 2. 配置filter

    @Bean
    public FilterRegistrationBean traceIdFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TraceIdFilter());
        registration.setName("traceIdFilter");
        registration.setOrder(2);
        registration.addUrlPatterns("/*");
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.INCLUDE, DispatcherType.ERROR);
        return registration;
    }

 

3.  json traceId 接口返回:

    

  

@ControllerAdvice
public class TraceIdAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(Map.class.isInstance(body)){
            Map map = (Map)body;
            map.put("traceId",MDC.get("traceId"));
        }
        return body;
    }
}

 

4. 日志配置:增加%X{traceId}

[%-5level] %d{${DATETIME}} [%thread] [%X{traceId}] %logger{36} - %m%n

 

 

 

你可能感兴趣的:(slf4j 日志增加traceId)