在SpringBoot REST API中记录运行时间 [英] Logging elapsed time of execution in SpringBoot rest API

查看:0
本文介绍了在SpringBoot REST API中记录运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的解决方案,但我做不到。 我需要在SpringBoot rest API中记录我的请求的总体执行时间。 请求始终进入MainController并可从两个位置退出-

  1. MainRestcontroller相同方法或
  2. ExceptionHandlerController处理程序方法
我已经创建了一个自定义注释,并将其注入到主ControllerExceptionController方法中,并获得各个方法的运行时间。 因此,问题就在这里。我需要将这些单独的时间相加,以计算我不需要的总时间。

是否有其他方法可以轻松记录此信息。

方面类:

@Aspect
@Component
public class PointsAspect {

    private final static Logger logger = LoggerFactory.getLogger(PointsAspect.class);

    @Around("@annotation(annotation)")
    public Object logMethod(final ProceedingJoinPoint proceedingJoinPoint, final LogAround annotation)
            throws Throwable {
        final long start = System.currentTimeMillis();
        Object obj;
        try {
            logger.debug("Starting...! Method Name - " +proceedingJoinPoint.getSignature().getName());
            obj = proceedingJoinPoint.proceed();
        } finally {
            logger.debug("Exiting...! Method Name - " +proceedingJoinPoint.getSignature().getName() +"Execution Time in Milliseconds:> "+ String.valueOf(System.currentTimeMillis()-start));
        }
        return obj;
    }
}

标记界面:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAround {

}

我是这样注入的:

**ExceptionHandlerController.java**

@LogAround
@ExceptionHandler(HttpMessageNotReadableException.class)
public GenericFailureResponse missingRequestBodyException(HttpServletResponse response,
            HttpServletRequest request, Exception ex) throws IOException {
        GenericFailureResponse failureResponse =  new GenericFailureResponse();
        //TODO: exception logic
        return failureResponse;
}



**MainController.java**

@LogAround
 public String getTotalPoints(@RequestParam(required=true) long memberNo,
            HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        //TODO : some logic
        return "something";
 }

推荐答案

可以使用简单的筛选器。

@Component
public class LogTimeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long startTime = System.currentTimeMillis();
        chain.doFilter(request, response);
        long duration = System.currentTimeMillis() - startTime;
        System.out.println("Request take " + duration + " ms");
    }
}

这篇关于在SpringBoot REST API中记录运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆