Log the method execution time using AOP for a spring boot application.

Krushna Dash
2 min readApr 1, 2020

--

We will use the spring AOP (Aspect-oriented programming) to avoid the boilerplate code like logging the method execution time. Spring AOP, aspects enable the modularization of concerns such as transaction management, logging or security that cut across multiple types and objects (often termed crosscutting concerns)

We have to add the spring-boot-starter-aop for the AOP programming like below.<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Then we have defined an aspect of type around advice. Around advice surrounds method invocation. Around advice can perform custom behavior before and after the method invocation. So using this we will capture the time before the method invocation and after method invocation we will use the time to calculate the execution time.

Here is an example of the Aspect class.

Let defined the annotation LogExecutionTime which will be applied at the method level, we have written the above class “around advice”, which will be applied to all the method annotated with this annotation.

After this, any method annotated with @LogExecutionTime, the around advice will be applied and it automatically logs the execution time.

Example

@GetMapping(“/hello”)
@LogExecutionTime
public ResponseEntity<String> getHello(){
return ResponseEntity.ok(“Welcome to AOP logging”);
}

The full code is at https://github.com/krushnaDash/spring-aop-log

--

--

Krushna Dash
Krushna Dash

Responses (2)