CommonsRequestLoggingFilter

CommonsRequestLoggingFilter

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

例如:

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

在处理请求之前和之后,我必须在过滤器中记录请求正文。

最佳答案

为此,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>

09-25 22:22