package cn.com.poc.common.interceptor;

import cn.com.yict.framemax.core.spring.mvc.MvcHandlerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author Focan Zhong
 * @create 2021/8/7
 */
public class TraceInterceptor implements MvcHandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String LOG_KEY = "log_trace_id";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        //生成日志追踪id
        try {
            String traceId = UUID.randomUUID().toString().replaceAll("-", "");
            MDC.put(LOG_KEY, traceId);
            response.setHeader("TraceId", traceId);
        } catch (Exception e) {
            logger.error("生成日志追踪id异常:" + e.getMessage(), e);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

        MDC.remove(LOG_KEY);
    }
}