package com.cf.imes.framework.tracer.core.filter;

import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

import static com.cf.imes.framework.common.enums.TraceConstants.TRACE_ID;

/**
 * Trace 过滤器，打印 traceId 到 header 中返回
 *
 * @author 晨丰科技
 */
public class TraceFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String traceId = UUID.randomUUID().toString();
        try {
            // 设置日志跟踪ID
            MDC.put(TRACE_ID, traceId);
            // 继续过滤
            chain.doFilter(request, response);
        } finally {
            // 清理跟踪ID
            MDC.remove(TRACE_ID);
        }
    }

}
