Skip to content

Instantly share code, notes, and snippets.

@joeytsai
Created June 29, 2017 03:05
Show Gist options
  • Select an option

  • Save joeytsai/3eda528668bbdd55fad004589e8a78b1 to your computer and use it in GitHub Desktop.

Select an option

Save joeytsai/3eda528668bbdd55fad004589e8a78b1 to your computer and use it in GitHub Desktop.
Spring RestTemplate logging
/*
You can setup an interceptor to read the raw HttpResponse, but it is an InputStream
1) Implement ClientHttpRequestInterceptor to execute the request, the log the response body InputStream
*/
class LoggingInterecptor : ClientHttpRequestInterceptor {
private val LOG = LoggerFactory.getLogger(javaClass)
override fun intercept(request: HttpRequest?, body: ByteArray?, execution: ClientHttpRequestExecution): ClientHttpResponse {
val response = execution.execute(request, body)
val payload: String = ByteArrayOutputStream().use {
response.body.copyTo(it)
it.toString()
}
LOG.debug("PAYLOAD> $payload")
return response
}
}
/*
However, if you read the InputStream, the response RestTemplate will have a null body, even if you don't close the InputStream
2) So, you must also set wrap the ClientHttpRequestFactory with a BufferingClientHttpRequestFactory
*/
val restTemplate2 = RestTemplate(BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory())).apply {
interceptors = listOf(LoggingInterecptor())
}
val restTemplate = RestTemplate().apply {
requestFactory = BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory())
interceptors = listOf(LoggingInterecptor())
}
// https://stackoverflow.com/questions/7952154/spring-resttemplate-how-to-enable-full-debugging-logging-of-requests-responses
// http://blog.cacoveanu.com/2016/06/24/rest-template-logging.html
// https://molchanoff.me/software-development/logging-spring-rest-template-requests/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment