Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Try to use WebFilter in Spring Boot Webflux in order to log request body
package com.blazemeter.dagger.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.io.IOException;
@Component
@Slf4j
public class ExampleWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
ObjectMapper mapper = new ObjectMapper();
return serverWebExchange
.getRequest()
.getBody()
.next()
.flatMap(body -> {
try {
return Mono.just(mapper.readValue(body.asInputStream(), String.class));
} catch (IOException e) {
return Mono.error(e);
}
})
.flatMap((String s) -> {
log.info(s);
return webFilterChain.filter(serverWebExchange);
});
}
}
@zzaoen

This comment has been minimized.

Copy link

@zzaoen zzaoen commented Mar 11, 2020

Hi, It seems not to work in Kotlin.
I changed the code to compatible with Kotlin, then the request body will be consumed in the first flatMap method, the body will not be able to consume by the handler method. Have you ever had this problem?
BTW, I got the solution in Kotlin, FYI, https://stackoverflow.com/questions/45240005/how-to-log-request-and-response-bodies-in-spring-webflux

@pgilad

This comment has been minimized.

Copy link
Owner Author

@pgilad pgilad commented Mar 11, 2020

Haven't tried, but if you can get a compatible code to work on both Java/Kotlin would gladly update the Java code

@62mkv

This comment has been minimized.

Copy link

@62mkv 62mkv commented Mar 19, 2020

for me this doesn't even work in Java... request is logged, but the controller seems to be hanging forever, as the request body is already consumed by that point. could you @pgilad share also actual controller? I can't figure what am I missing..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.