springMVC拦截器实现日志记录请求耗时

定义拦截器

public class LogTimeHandlerInterceptor extends HandlerInterceptorAdapter {
 // 单例多线程 开始时间绑定在线程上
    private ThreadLocal startTimeThreadLocal = new ThreadLocal<>();
    private static final Logger log = LoggerFactory.getLogger("RequestTime");
 //获取请求前时间并放入startTimeThreadLocal 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        long start = System.currentTimeMillis();
        startTimeThreadLocal.set(start);
        return true;
    }
//请求结束后计算出耗时 日志记录相关信息
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod method = (HandlerMethod) handler;
                String className = method.getBeanType().getName();
                String methodName = method.getMethod().getName();
                Long startTime = startTimeThreadLocal.get();
                Long endTime = System.currentTimeMillis();
                StringBuilder logs = new StringBuilder();
              //可在此处获取当前用户放日志信息里 
                logs.append(" IP:").append(HttpUtil.getIpAddress(request));//获取请求地址IP 自己实现 
                logs.append(" ").append(className).append("::").append(methodName);
                long time = endTime - startTime;
                logs.append(" 耗时:").append(time).append("(ms)");
                log.info(logs.toString());
            }
        } finally {
             //清理开始时间
            startTimeThreadLocal.remove();
        }
    }
}

可以根据需求记录更多信息,也可以把日子信息存入数据库。

配置拦截器(基于springBoot)

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LogTimeHandlerInterceptor());
        }
}

效果如下


image.png

你可能感兴趣的:(springMVC拦截器实现日志记录请求耗时)