在Spring Boot中记录请求有效负载

时间:2017-09-19 02:59:40

标签: java spring spring-boot spring-restcontroller

如何在Spring Boot应用程序的过滤器中处理之前和之后记录请求有效负载/参数。

例如:

/api/users/auth Body: `name:Vijay, place:bangalore...`

我必须在处理请求之前和之后在过滤器中记录请求主体。

1 个答案:

答案 0 :(得分:6)

Spring Boot为此提供了CommonsRequestLoggingFilter

您可以这样配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CommonsRequestLoggingFilter;


@Configuration
public class RequestLoggingFilterConfigurer {

    @Bean
    public CommonsRequestLoggingFilter requestLoggingFilter() {
        CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
        filter.setIncludeQueryString(true);
        filter.setIncludePayload(true);
        // truncate payloads
        filter.setMaxPayloadLength(1000);
        filter.setIncludeHeaders(false);
        filter.setAfterMessagePrefix("Request received: ");
        return filter;
    }
}

并向您的logback.xml添加记录器定义,如下所示:

<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter" level="DEBUG">
    <appender-ref ref="REQUEST_RESPONSE_FILE_APPENDER"/>
</logger>