Skip to content

Instantly share code, notes, and snippets.

@pgilad
Last active June 17, 2021 08:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pgilad/e2d77ea2be972589f8ac475a88484dc5 to your computer and use it in GitHub Desktop.
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
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
Copy link

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
Copy link
Author

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
Copy link

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