How do I log response in Spring RestTemplate?

Viewed 36588

I am using RestTemplate to make calls to a web service.

String userId = restTemplate.getForObject(createUserUrl, String.class);

If this fails to return a user ID I just get returned null but I don't know why. How do I output the actual XML response to a log?

5 Answers

You can use spring-rest-template-logger to log RestTemplate HTTP traffic.

Add a dependency to your Maven project:

<dependency>
    <groupId>org.hobsoft.spring</groupId>
    <artifactId>spring-rest-template-logger</artifactId>
    <version>2.0.0</version>
</dependency>

Then customize your RestTemplate as follows:

RestTemplate restTemplate = new RestTemplateBuilder()
    .customizers(new LoggingCustomizer())
    .build()

Ensure that debug logging is enabled in application.properties:

logging.level.org.hobsoft.spring.resttemplatelogger.LoggingCustomizer = DEBUG

Now all RestTemplate HTTP traffic will be logged to org.hobsoft.spring.resttemplatelogger.LoggingCustomizer at debug level.

DISCLAIMER: I wrote this library.

If you used swagger to generate the RestTemplate based client then in the ApiClient there is a public method setDebugging and you can set to true or false and then I was able to see whats going on. Hope this helps. I used latest swager generator cli I think its 2.9 or something

you don't need to write a single line of code, you just need to add the following property in application.properties file

logging.level.org.springframework.web.client.RestTemplate=DEBUG

using this it will log rest template call's request body, request header, request URL, and response body also in debug mode.

Related