package com.liquidnet.common.web.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

@Slf4j
@Component
public class GlobalLogTrackInterceptor extends HandlerInterceptorAdapter {
    private static final String LNS_TRANCE_ID = "lnsTranceId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String t = MDC.get(LNS_TRANCE_ID);
        MDC.put(LNS_TRANCE_ID, null == t ? String.valueOf(System.nanoTime()) : t);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long e = Long.parseLong(MDC.get(LNS_TRANCE_ID));
        log.info("[{}]耗时:{}ms", request.getRequestURI(), (System.nanoTime() - e) / 1000000);
        MDC.clear();
    }
}
