com.bizmda.log.trace.RestTemplateTraceInterceptor Maven / Gradle / Ivy
package com.bizmda.log.trace;
import org.slf4j.MDC;
import org.springframework.http.HttpHeaders;
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.StringUtils;
import java.io.IOException;
public class RestTemplateTraceInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
HttpHeaders headers = httpRequest.getHeaders();
String traceId = MDCTraceUtils.getTraceId();
if (!StringUtils.isEmpty(traceId)) {
headers.add(MDCTraceUtils.TRACE_ID_HEADER,traceId);
}
String value;
for(String istioKey:MDCTraceUtils.ISTIO_TRACE_HEADERS) {
value = MDC.get(istioKey);
if (!StringUtils.isEmpty(value)) {
headers.add(istioKey,value);
}
}
return clientHttpRequestExecution.execute(httpRequest, bytes);
}
}