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
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.