How can I log RESTful post data?

前端 未结 3 1315
离开以前
离开以前 2020-12-31 09:18

We have REST services exposed via Spring MVC. We use a HandlerExceptionResolver to log exceptions. We currently log the following:

  • The exception
相关标签:
3条回答
  • 2020-12-31 09:31

    You need a filter that would save request body when it's being read and provide the saved data to your exception logger later.

    Spring contains AbstractRequestLoggingFilter that does the similar thing. Though it's not directly suitable for your problem, you can use it as a reference to implement your own filter.

    0 讨论(0)
  • 2020-12-31 09:35

    Add this to the class representing the configuration for the application:

    import javax.servlet.Filter;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.web.filter.AbstractRequestLoggingFilter;
    

    ....

    @Bean
    public Filter loggingFilter(){
        AbstractRequestLoggingFilter f = new AbstractRequestLoggingFilter() {
    
            @Override
            protected void beforeRequest(HttpServletRequest request, String message) {
                System.out.println("beforeRequest: " +message);
            }
    
            @Override
            protected void afterRequest(HttpServletRequest request, String message) {
                System.out.println("afterRequest: " +message);
            }
        };
        f.setIncludeClientInfo(true);
        f.setIncludePayload(true);
        f.setIncludeQueryString(true);
    
        f.setBeforeMessagePrefix("BEFORE REQUEST  [");
        f.setAfterMessagePrefix("AFTER REQUEST    [");
        f.setAfterMessageSuffix("]\n");
        return f;
    }
    

    you may have to comment out

       f.setIncludePayload(true);
    
    0 讨论(0)
  • 2020-12-31 09:46

    There is no easy way to log the payload of the request/response. You can use a java web filter to intercept all the requests and responses and read the JSON data from the stream. But there is one problem, when you will read data from the stream the actual data will be exhausted from stream.

    Therefore, you have to implement the wrapper of actual request and response object. Only the copied version of request response will be logged. We have implemented similar solution like follows and it satisfied our requirement:

    http://www.wetfeetblog.com/servlet-filer-to-log-request-and-response-details-and-payload/431

    http://angelborroy.wordpress.com/2009/03/04/dump-request-and-response-using-javaxservletfilter/

    0 讨论(0)
提交回复
热议问题