Logging POST request body in Web Flux

怎甘沉沦 提交于 2019-12-24 18:33:50

问题


I am trying to log request body in web-flux following : webflux-demo But I end up with empty string all the time even when I pass request body. The requestBody.map does not get executed. It skips the block. What am I missing?

    @Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    if(logging.enabled()){
        ServerHttpRequest request = exchange.getRequest();
        System.out.println("Request body : " + getRequestBody(request));
        return chain.filter(exchange);
    } else {
        return chain.filter(exchange);
    }
}

private String getRequestBody(ServerHttpRequest request) {
    final ServerHttpRequest decorated = new ServerHttpRequestDecorator(request);
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    Flux<DataBuffer> requestBody = decorated.getBody();
    requestBody.map(dataBuffer -> {
        try {
            Channels.newChannel(byteArrayOutputStream)
                .write(dataBuffer.asByteBuffer().asReadOnlyBuffer());
        } catch (IOException e) {
            logger.error("Unable to log input request due to an error", e);
        }
        return dataBuffer;
    });

    return byteArrayOutputStream.toString();
}

来源:https://stackoverflow.com/questions/59435754/logging-post-request-body-in-web-flux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!