如何记录spring webclient请求和响应主体?

时间:2019-11-11 01:08:22

标签: java spring spring-mvc spring-webflux spring-webclient

向WebClient添加了一个ExchangeFilterFunction来记录请求和响应,但是在记录时无法将请求和响应主体记录为字符串或JSON。它将作为对象打印

尝试了不同的转换,并使用bodyToMono toEntity将其作为字符串检索,但是它们返回一个对象而不是完全字符串。

        logRequest(clientRequest.url(), clientRequest.method(), clientRequest.headers(), clientRequest.body());
        Mono<ClientResponse> response = exchangeFunction.exchange(clientRequest);
        ClientResponse clientResponse = response.block();

      logResponse(clientResponse.statusCode(), clientResponse.headers(), clientResponse.toString(), clientResponse);

        return response;
    }```

```private void logRequest(URI uri, HttpMethod method, HttpHeaders httpHeaders, BodyInserter<?, ? super ClientHttpRequest> body) {

        log.info("Request: {}", 
                 LogVar.with("Body", body)
        );
    }

    private void logResponse(HttpStatus statusCode, Headers headers, String body, ClientResponse extractor) {
        log.info("Response: {}", 
                 , LogVar.with("Body", extractor.bodyToMono(String.class))
        );
    }```

Expecting Json OR XML whatever the request/response is, to be logged as a string.

0 个答案:

没有答案