public class WebInterceptor extendsHandlerInterceptorAdapter {private static Logger logger = Logger.getLogger(WebInterceptor.class);private static final String SYSTEM_ID= "BLOAN-GJJ";private static final String APP_ID= "gjj-ics-credit";private static final String TYPE = "java";private static final Histogram requestLatency =Histogram.build()
.name("service_requests_latency_seconds")
.help("Request latency in seconds.")
.labelNames("systemId", "appId", "type", "name", "method").register();private ThreadLocaltimerThreadLocal;
@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throwsException {return super.preHandle(request, response, handler);
}
@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throwsException {
String name= this.getName(request, handler).toLowerCase();
String method=request.getMethod().toUpperCase();
timerThreadLocal= new ThreadLocal<>();
timerThreadLocal.set(requestLatency.labels(SYSTEM_ID, APP_ID, TYPE, name, method).startTimer());super.postHandle(request, response, handler, modelAndView);
}
@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throwsException {super.afterCompletion(request, response, handler, ex);if (timerThreadLocal.get() != null) {
timerThreadLocal.get().observeDuration();
}
}
@Overridepublic void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throwsException {super.afterConcurrentHandlingStarted(request, response, handler);
}privateString getName(HttpServletRequest request, Object handler) {
String name= "";try{if (handler != null
&& handler instanceofHandlerMethod) {
HandlerMethod method=(HandlerMethod) handler;
String className=((HandlerMethod) handler).getBeanType().getName();
name= className + "." +method.getMethod().getName();
}else{
name=request.getRequestURI();
}
}catch(Exception ex) {
logger.error("getName", ex);
}finally{returnname;
}
}
}