0

I am looking to store the (post / put) request and responses of a few specific endpoints on the database.

Is it wise to do this with interceptors (handlerInceptor) ? Can I autowire the service that calls the database to the interceptor ? I mean there are other interceptors that take care of auth / logging. I'm planning to add this as a last interceptor, if that makes sense.

1 Answers1

1

From the good OOP codebase 's point of view , it makes a lot of sense and even a good practise to do it as it promote SRP which has a service class just focus on doing the logging stuff but not how to get the things that need to be logged from the environment.

The logging service should be designed to be as generic as possible such that it knows nothing about its environment such as HttpServletRequest and HttpServletResponse in order to be reused easily it in other context (e.g. used to log the message consumed from a broker)

The HandlerInterceptor is the client to call the logging service . In there you can access the environment stuff which in your case is HttpServletRequest and HttpServletResponse. It responsibility is to determine if the current HTTP request is required to be logged , and prepare the things that need to be logged from the HTTP request , and just pass it to the logging service for doing the actual logging.

For the performance 's point of view , you may look into the concept of asynchronous logging (e.g refer here for the log4j2 case). You still start from HandlerInterceptor but do not call the logging service directly in the same thread but tell other threads to do it asynchronously.

Ken Chan
  • 84,777
  • 26
  • 143
  • 172