How can I log RESTful post data?

2019-02-06 10:29发布

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

  • The exception and its stack trace
  • The URL
  • The request headers

It would make debugging easier if we could also log the JSON post data as well. Any suggestions on how to get this?

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-06 10:56

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);
查看更多
戒情不戒烟
3楼-- · 2019-02-06 11:06

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/

查看更多
forever°为你锁心
4楼-- · 2019-02-06 11:07

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.

查看更多
登录 后发表回答