0

I have to save all API request along with response to database in Spring Boot application.

I should save following:

request URL
request parameters
request body
response body

How can I do it generically so that I don't need to write code in every method ? Please suggest how to do that

Krish
  • 1,804
  • 7
  • 37
  • 65
  • Using an Interceptor? https://www.baeldung.com/spring-mvc-handlerinterceptor – Alan Hay Feb 26 '19 at 14:11
  • Spring provides actuators it may be helpful or you can [refer to this question](https://stackoverflow.com/questions/33744875/spring-boot-how-to-log-all-requests-and-responses-with-exceptions-in-single-pl) – Romil Patel Feb 27 '19 at 06:50

1 Answers1

0

There seem to be plenty of examples on how to log those using filters, so you can inject a repository into one and have it save instead of logging.

Edit - sorry, failed to include chain.doFilter(request, response);

  //Filter
    @Component
    public class RequestResponseLoggingFilter implements Filter {

        private final Logger LOGGER = LoggerFactory.getLogger(Application.class);

        //Inject repo here

        @Override
        public void doFilter(
          ServletRequest request, 
          ServletResponse response, 
          FilterChain chain) throws IOException, ServletException {

            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;

            //Read data from req and res, save to repo
            LOGGER.info("Logged : " + req.getRequestURI());

            chain.doFilter(request, response);
        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {}

        @Override
        public void destroy() {}
    }
    @Bean
    public FilterRegistrationBean<RequestResponseLoggingFilter> loggingFilter(){
        FilterRegistrationBean<RequestResponseLoggingFilter> registrationBean 
          = new FilterRegistrationBean<>();

        registrationBean.setFilter(new RequestResponseLoggingFilter());
        registrationBean.addUrlPatterns("/**");

        return registrationBean;    
    }

Unable to autowire the service inside my authentication filter in Spring is something you'll probably need.

Ivan Furdek
  • 711
  • 6
  • 6
  • the code you provided is not working for me. can you please provide complete code or any blog ? – Krish Feb 28 '19 at 05:26
  • Blog with working filter implementation - https://www.javadevjournal.com/spring-boot/spring-boot-add-filter/ – Ivan Furdek Feb 28 '19 at 08:58