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

 

posted @ 2024-07-09 22:36  天门道人  阅读(182)  评论(0编辑  收藏  举报