【问题标题】:Log execution time of each method of the request using Spring AOP使用Spring AOP记录请求的各个方法的执行时间
【发布时间】:2019-01-12 17:34:37
【问题描述】:

假设我有一个具有简单架构(控制器、服务、存储库)的基本 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
 }

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

【问题讨论】:

  • 在最顶层创建ThreadLocal(例如,在您的情况下为控制器,或者更好地已经在某些servlet过滤器中),并使用唯一的请求跟踪号并将其与每个较低的时间信息一起记录水平。

标签: spring-boot logging slf4j spring-aop


【解决方案1】:

跟踪每个请求的时间。

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

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

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

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多