SpringBoot项目日志自动添加追踪ID
1. 添加Filter
@Component public class TraceIdFilter extends OncePerRequestFilter { private static final String TRACE_ID = "traceId"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String traceId = UUID.randomUUID().toString(); MDC.put(TRACE_ID, traceId); filterChain.doFilter(request, response); } finally { MDC.clear(); } } }
2.配置文件
logging.pattern.console=%d{HH:mm:ss.SSS} [%thread] %-5level %C.%M [traceId: %X{traceId}] - %msg%n