package com.bicloud.Interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;


/*
拦截器,请求打印请求状态
 */
@Component
public class RequestLogInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(RequestLogInterceptor.class);
    private static final String START_TIME = "REQ_START_TIME";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute(START_TIME, System.currentTimeMillis());

        log.info("[REQ] time={}, method={}, uri={}, ip={}",
                LocalDateTime.now(),
                request.getMethod(),
                request.getRequestURI(),
                request.getRemoteAddr());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        Long start = (Long) request.getAttribute(START_TIME);
        long cost = (start == null) ? -1 : (System.currentTimeMillis() - start);

        if (ex == null) {
            log.info("[RES] status={}, costMs={}, uri={}",
                    response.getStatus(), cost, request.getRequestURI());
        } else {
            log.warn("[RES] status={}, costMs={}, uri={}, ex={}",
                    response.getStatus(), cost, request.getRequestURI(), ex.toString());
        }
    }
}

