使用SpringAOP记录请求的每个方法的执行时间



假设我有一个基本的Spring引导应用程序,它有一个简单的体系结构(Controller、Service、Repository(。我试图记录应用程序中每个层的执行时间(以及每个层的不同内容(,我试图使用带有@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。我希望每个请求都有一个单行日志。

跟踪每个请求的时间。

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

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

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

最新更新