1、建立一个过滤器,在过滤器中给线程设置TraceId
2、将日志的配置文件进行修改,把TraceId打印到日志中
@Order(1)
@WebFilter(urlPatterns = "/*")
public class TraceldFilter implements Filter{
private static final String TRACE_ID="traceId";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 给每一个线程分配一个traceId
String traceId=request.getParameter(TRACE_ID);
if(StringUtils.isBlank(traceId)) {
traceId=UUID.randomUUID().toString();
}
MDC.put(TRACE_ID, traceId);
chain.doFilter(request, response);
}
}
application.properties
logging.pattern.console= %d [%thread] %-5p [%c] [%F:%L][traceId:%clr(%X{traceId})] - %msg%n
@SpringBootApplication
@ServletComponentScan
public class AllLearningApplication {
public static void main(String[] args) {
SpringApplication.run(AllLearningApplication.class, args);
}
}
这个方案还是比较简陋的,有时间再看看好的方案
网友评论