How to log request body in spring Webflux Java

前端 未结 1 831
挽巷
挽巷 2021-01-26 17:58

I am receiving some XML payload in a POST request and want to see the payload as received for debugging purposes.

Below (my custom WebFilter) code logs the URI and reque

相关标签:
1条回答
  • 2021-01-26 18:24

    You are doing it partially right except that you are extracting the body at the wrong place. You will have to do it in a ServerHttpRequestDecorator implementation and plug it in the WebFilter implementation.

    public class RequestLoggingDecorator extends ServerHttpRequestDecorator {
    
      private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggingDecorator.class);
    
      public RequestLoggingDecorator(ServerHttpRequest delegate) {
        super(delegate);
      }
    
      @Override
      public Flux<DataBuffer> getBody() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        return super.getBody().doOnNext(dataBuffer -> {
          try {
            Channels.newChannel(baos).write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
            String body = new String(baos.toByteArray(), StandardCharsets.UTF_8);
            LOGGER.info("Request: payload={}", body);
          } catch (IOException e) {
            e.printStackTrace();
          } finally {
            try {
              baos.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        });
      }
    }
    

    Then you can configure this in a WebFilter implementation as follows:

    @Configuration
    public class RequestLoggingFilter implements WebFilter {
      @Override
      public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        ServerWebExchangeDecorator decorator =
            new ServerWebExchangeDecorator(serverWebExchange) {
              @Override
              public ServerHttpRequest getRequest() {
                return new RequestLoggingDecorator(serverWebExchange.getRequest());
              }
            };
    
        return webFilterChain.filter(decorator);
      }
    }
    

    This should log your request body on every incoming Http request.

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