Last active
January 9, 2022 16:31
-
-
Save Linkit123/4204b758e3fe80b5861a5cd426b7d0c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dvtt.demo.coredemo.interceptor; | |
import com.dvtt.demo.coredemo.thread.ThreadContextKeeper; | |
import lombok.AllArgsConstructor; | |
import lombok.extern.slf4j.Slf4j; | |
import org.springframework.http.HttpRequest; | |
import org.springframework.http.client.ClientHttpRequestExecution; | |
import org.springframework.http.client.ClientHttpRequestInterceptor; | |
import org.springframework.http.client.ClientHttpResponse; | |
import org.springframework.util.StreamUtils; | |
import java.io.IOException; | |
import java.nio.charset.Charset; | |
import java.nio.charset.StandardCharsets; | |
@Slf4j | |
@AllArgsConstructor | |
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor { | |
@Override | |
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { | |
logRequest(request, body); | |
ClientHttpResponse response = execution.execute(request, body); | |
logResponse(response); | |
return response; | |
} | |
private void logRequest(HttpRequest request, byte[] body) { | |
String requestId = ThreadContextKeeper.getRequestAttributes().getRequestId(); | |
request.getHeaders().add("request_id", requestId); | |
log.info("===========================request begin {}================================================", requestId); | |
log.info("URI : {}", request.getURI()); | |
log.info("Method : {}", request.getMethod()); | |
log.info("Headers : {}", request.getHeaders()); | |
log.info("Request body: {}", new String(body, StandardCharsets.UTF_8)); | |
log.info("==========================request end {}================================================", requestId); | |
} | |
private void logResponse(ClientHttpResponse response) throws IOException { | |
String requestId = ThreadContextKeeper.getRequestAttributes().getRequestId(); | |
log.info("============================response begin {}==========================================", requestId); | |
log.info("Status code : {}", response.getStatusCode()); | |
log.info("Status text : {}", response.getStatusText()); | |
log.info("Headers : {}", response.getHeaders()); | |
log.info("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset())); | |
log.info("==========================request end {}================================================", requestId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment