Last active
June 17, 2021 08:02
-
-
Save pgilad/e2d77ea2be972589f8ac475a88484dc5 to your computer and use it in GitHub Desktop.
Try to use WebFilter in Spring Boot Webflux in order to log request body
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); | |
} | |
} |
Haven't tried, but if you can get a compatible code to work on both Java/Kotlin would gladly update the Java code
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
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