首页 > 解决方案 > 使用Spring AOP记录请求的各个方法的执行时间

问题描述

假设我有一个具有简单架构(控制器、服务、存储库)的基本 Spring 引导应用程序。我正在尝试记录应用程序中每一层的执行时间(以及每一层的不同内容),我正在尝试使用带有@Around Aspect 的 Spring AOP 来执行此操作。问题是该应用程序是一个并发应用程序,并且可以同时出现多个请求,所以如果我这样做:

 @Around("controller() || restController() ")
 public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("time elapsed" + timeElapsed)
    //Log some other Controller useful info
 }

 @Around("service() ")
 public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("time elapsed" + timeElapsed)
    //Log some other Service useful info
 }

 @Around("repository() ")
 public Object logAround(final ProceedingJoinPoint joinPoint) throws Throwable {
    log.info("time elapsed" + timeElapsed)
    //Log some other Repository useful info
 }

我将无法跟踪每个请求的日志,因为一次可能会发生多个并发请求。我正在使用带有 lombok 实现的 SLF4J,但我认为我可以切换到 SLF4J 的任何其他实现,例如 log4j,如果它对我想要的有任何影响。我希望每个请求都有一个单行日志。

标签: spring-bootloggingslf4jspring-aop

解决方案


跟踪每个请求的时间。

  • 通过更改日志格式如下添加线程 id 作为日志记录的一部分
    线程 id 对于每个请求都是唯一的

    %d %-5level [%thread] [%logger{36}] : %msg%n%rEx

  • 当您记录每一层的时间性能时,将性能日志重定向到单独的文件。


推荐阅读