A popular approach for logging requests and responses is to use spring-aop. However, it is recommended not to do performance intensive operations on spring-aop. This is an example of using spring-aop in your use case. However, rather than querying the DB everytime for request or response log it is better if you could find a way to process the logs in batches to avoid DB access overhead.
Add the spring-boot-starter-aop dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Enable AspectJAutoproxy for the spring application
@SpringBootApplication( )
@EnableAspectJAutoProxy( proxyTargetClass = true )
public class Application
{
public static void main( String[] args )
{
SpringApplication.run( Application.class, args );
}
}
Add the aspect class
@Aspect
@Component
public class CalculatorAspect
{
private Logger LOGGER = Logger.getLogger( getClass().getName() );
@Around( "execution(* com.example.Calculator.add(..))" ) // Add method
public Object logInfoAboutAddOperation( ProceedingJoinPoint joinPoint ) throws Throwable
{
// Log here for request using joinPoint variable information
// and add the necessary entries to DB
Object proceed = joinPoint.proceed(); // This instructs the target to proceed with method execution which is the add() method
// Log here for response and add the necessary info to DB
return proceed; // This is mandatory and this contains the result of add() method. You can even change the actual result here
}
}
There are various ways this can be done to suit your requirement. Please have a look at this link for more information about spring-aop. By using the relevant Advice you can log request and responses at Controller layer too.