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

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Krushna Dash
Krushna Dash

Written by Krushna Dash

Principal Software Engineer at Walmart

Responses (2)

Write a response