This article mainly introduces how to use spring stopwatch in detail. The example code is introduced in detail, which has certain reference value for everyone’s study or work. Friends in need can refer to it
Stopwatch is a simple stopwatch that allows multiple tasks to be timed, exposing the total run time and run time of each named task. Hidden use System.currentTimeMillis (), improve the readability of application code and reduce the possibility of computational errors.
The following demonstration uses stopwatch to record request summary log information:
@Slf4j
public class PerformanceInteceptor implements HandlerInterceptor {
private ThreadLocal<StopWatch> stopWatchThreadLocal = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
StopWatch sw = new StopWatch();
stopWatchThreadLocal.set(sw);
sw.start();
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
stopWatchThreadLocal.get().stop();
stopWatchThreadLocal.get().start();
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
StopWatch sw = stopWatchThreadLocal.get();
sw.stop();
String method = handler.getClass().getSimpleName();
if (handler instanceof HandlerMethod) {
String beanType = ((HandlerMethod) handler).getBeanType().getName();
String methodName = ((HandlerMethod) handler).getMethod().getName();
method = beanType + "." + methodName;
}
// sw.getTotalTimeMillis (), total execution time
// sw.getTotalTimeMillis () - sw.getLastTaskTimeMillis (), the time required to execute the method body
log.info("{};{};{};{};{}ms;{}ms;{}ms", request.getRequestURI(), method,
response.getStatus(), ex == null ? "-" : ex.getClass().getSimpleName(),
sw.getTotalTimeMillis(), sw.getTotalTimeMillis() - sw.getLastTaskTimeMillis(),
sw.getLastTaskTimeMillis());
stopWatchThreadLocal.remove();
}
}
The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.