Issue
I've started using WebClient and I'm adding logging of request/response using filter method:
WebClient.builder()
.baseUrl(properties.getEndpoint())
.filter((request, next) -> {
// logging
request.body()
})
.build();
I'm able to access url, http method, headers but I've a problem with getting raw request body as body()
method of request returns BodyInserter
(BodyInserter<?, ? super ClientHttpRequest> body()
.
How to convert BodyInserter
to String
representation of request body? Alternatively, how to properly log whole request/response while also being able to hash potential credentials in it?
Solution
Coming back to the topic with an answer I am so far satisfied.
In following example I created HttpClient
with LoggingHandler that does the logging magic, injected it into ReactorClientHttpConnector
which was default HttpConnector
(see DefaultWebClientBuilder#initConnector
) and then to WebClient
.
val baseHttpClient = HttpClient.create()
.doOnRequest(
(request, conn) -> conn.addHandlerFirst(new LoggingHandler(LogLevel.INFO)
));
val httpClient = WebClient.builder()
.baseUrl("https://google.pl")
.clientConnector(new ReactorClientHttpConnector(baseHttpClient))
.build();
val response = httpClient.post()
.body(Mono.just("Your request body"), String.class)
.exchangeToMono(clientResponse -> clientResponse.bodyToMono(String.class))
.block();
I'm still planning on creating custom LoggingHandler
which will sanitise and simplify logs.
Answered By - Marcin Szulc
Answer Checked By - Marilyn (JavaFixing Volunteer)