Skip to content

Instantly share code, notes, and snippets.

@CharlesLuxinger
Created April 1, 2021 17:55
Show Gist options
  • Save CharlesLuxinger/d94bcb4a018595de0610d373240d6117 to your computer and use it in GitHub Desktop.
Save CharlesLuxinger/d94bcb4a018595de0610d373240d6117 to your computer and use it in GitHub Desktop.
RestTemplate Logging Json Body Config
import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
import java.util.ArrayList
import java.util.stream.Collectors
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpRequest
import org.springframework.http.client.BufferingClientHttpRequestFactory
import org.springframework.http.client.ClientHttpRequestExecution
import org.springframework.http.client.ClientHttpRequestFactory
import org.springframework.http.client.ClientHttpRequestInterceptor
import org.springframework.http.client.ClientHttpResponse
import org.springframework.http.client.SimpleClientHttpRequestFactory
import org.springframework.web.client.RestTemplate
@Configuration
class RestTemplateConfig {
@Bean
fun restTemplate(): RestTemplate {
val factory: ClientHttpRequestFactory = BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory())
val restTemplate = RestTemplate(factory)
var interceptors = restTemplate.interceptors
if (interceptors.isEmpty()) {
interceptors = ArrayList()
}
interceptors.add(LoggingInterceptor())
restTemplate.interceptors = interceptors
return restTemplate
}
}
class LoggingInterceptor : ClientHttpRequestInterceptor {
var log: Logger = LoggerFactory.getLogger(LoggingInterceptor::class.java)
override fun intercept(
req: HttpRequest,
reqBody: ByteArray,
ex: ClientHttpRequestExecution
): ClientHttpResponse {
log.debug("Request body: {}", String(reqBody, StandardCharsets.UTF_8))
val response: ClientHttpResponse = ex.execute(req, reqBody)
val isr = InputStreamReader(response.body, StandardCharsets.UTF_8)
val body = BufferedReader(isr).lines().collect(Collectors.joining("\n"))
log.debug("Response body: {}", body)
return response
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment