package com.hz.pm.api.common.interceptor;

import cn.hutool.core.lang.UUID;
import com.hz.pm.api.common.util.MDCUtil;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * LogInterceptor
 * </p>
 *
 * @author WendyYang
 * @since 2023/10/26
 **/
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) {
        String traceId = UUID.randomUUID().toString(true);
        response.addHeader(MDCUtil.TRACE_ID_HEADER, traceId);
        MDCUtil.setTraceId(traceId);
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request,
                                @NonNull HttpServletResponse response,
                                @NonNull Object handler, Exception ex) {
        MDCUtil.removeTraceId();
    }

}
