package com.sckw.log.interceptor;

import com.sckw.log.utils.UuidUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @desc: 日志拦截器
 * @author: yzc
 * @date: 2023-08-23 10:38
 */
@Slf4j
@Configuration
public class LogInterceptor implements HandlerInterceptor {
    private static final String TRACE_ID = "traceId";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = request.getHeader(TRACE_ID);
        if (!StringUtils.hasText(traceId)) {
            MDC.put(TRACE_ID, UuidUtils.getUuid());
        } else {
            MDC.put(TRACE_ID, traceId);
        }
        return true;
    }

}
