Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Log the method, URL, status and duration of every outgoing call made with Spring's RestClient without logging secrets.

We implement a ClientHttpRequestInterceptor that records the start time, calls execution.execute(request, body), and then logs request.getMethod(), a masked request.getURI(), response.getStatusCode() and the duration, and we register it with RestClient.builder().requestInterceptor(interceptor). We never log Authorization, Cookie or API key headers, and we mask query parameters that carry tokens. Bodies are left out by default, because logging them needs buffering (BufferingClientHttpRequestFactory) that costs memory, and with Spring Boot, Micrometer observation already records http.client.requests metrics and traces for every call.

Why this question is asked

When a dependency misbehaves, the first question in an incident is "what did we send, and what came back, and how long did it take?". A one-line log per outgoing call answers it. The danger is in the details: logging a full URL with an access token in it, or an Authorization header, puts secrets into a log system many people can read. Interviewers ask for this in code because it combines a Spring extension point with security judgement. In this answer, we will recap how interceptors work in RestClient, write the interceptor, register it, make it safe for secrets, look at body logging and its costs, and connect it with the metrics Spring Boot already gives us.

1A Quick Recap of ClientHttpRequestInterceptor

RestClient sends each request through a chain of interceptors before it reaches the underlying HTTP library. An interceptor implements ClientHttpRequestInterceptor, which has one method, intercept(request, body, execution). It receives the request (method, URI, headers), the request body as bytes, and an execution object. Calling execution.execute(request, body) passes the request on to the next interceptor or, at the end, sends it, and returns the response. So code before that call runs before the request is sent, and code after it runs once the response status and headers have arrived. That makes it the natural place to measure and log each call.

2Writing the Logging Interceptor

Here is the interceptor. It logs one line on success and one on failure.

Java
public class OutboundLoggingInterceptor implements ClientHttpRequestInterceptor {
private static final Logger log = LoggerFactory.getLogger(OutboundLoggingInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
long start = System.nanoTime();
try {
ClientHttpResponse response = execution.execute(request, body);
log.info("{} {} -> {} in {} ms", request.getMethod(), SafeUri.mask(request.getURI()),
response.getStatusCode().value(), (System.nanoTime() - start) / 1_000_000);
return response;
} catch (IOException e) {
log.warn("{} {} -> failed ({}) in {} ms", request.getMethod(), SafeUri.mask(request.getURI()),
e.getClass().getSimpleName(), (System.nanoTime() - start) / 1_000_000);
throw e;
}
}
}
// GET https://inventory.internal/stock/A-1 -> 200 in 23 ms
// POST https://payments.internal/authorisations -> 503 in 1204 ms
// GET https://partner.example.com/rates?api_key=*** -> failed (SocketTimeoutException) in 5003 ms
Step throughWhere the interceptor sits
Our codeLogging interceptorHTTP libraryRemote API
GET /stock/A-1
start = nanoTime()
execution.execute(request, body)
request sent
200 + headers
ClientHttpResponse
log method, masked URI, 200, 23 ms
response, body read by caller

8 messages in order. Play them, or step through them one at a time.

Notice two details. We use System.nanoTime() for the duration, because it measures elapsed time reliably while the wall clock can jump. And the duration covers the time until the status and headers arrived, not the time to read the whole body, because the body is read by the caller after the interceptor returns. For most APIs the difference is small; for large downloads it matters, and the Micrometer metric described below covers the full exchange. On failure we log the exception type only, not its message, since messages can contain URLs, and we rethrow so callers still see the error.

3Registering the Interceptor

We add the interceptor to the builder. With Spring Boot, a RestClientCustomizer bean applies it to every RestClient built from the auto-configured builder, so teams do not have to remember it per client.

Java
@Bean
RestClientCustomizer outboundLogging() {
return builder -> builder.requestInterceptor(new OutboundLoggingInterceptor());
}
// Or for one client:
RestClient client = RestClient.builder()
.baseUrl("https://inventory.internal")
.requestInterceptor(new OutboundLoggingInterceptor())
.build();

4Keeping Secrets Out of the Logs

Our interceptor never logs headers, which is the simplest way to keep Authorization, Cookie, Set-Cookie and API key headers such as X-Api-Key out of the logs. If we ever need some headers for debugging, we log an allow-list of harmless ones, such as Content-Type or a request id, never a deny-list, because a deny-list misses the next secret header someone adds.

URLs need care too. Some APIs take tokens or signatures in the query string, and URLs can even contain user credentials in the user-info part (https://user:password@host). So we rebuild the URI with those parts masked.

Java
final class SafeUri {
private static final Set<String> SECRET = Set.of("token", "access_token", "api_key", "apikey", "signature", "sig", "password");
static String mask(URI uri) {
UriComponentsBuilder b = UriComponentsBuilder.fromUri(uri).userInfo(null); // drop user:password@
UriComponentsBuilder.fromUri(uri).build().getQueryParams().keySet().stream()
.filter(k -> SECRET.contains(k.toLowerCase(Locale.ROOT)))
.forEach(k -> b.replaceQueryParam(k, "***"));
return b.build().toUriString();
}
}
// https://partner.example.com/rates?api_key=abc123&from=USD -> https://partner.example.com/rates?api_key=***&from=USD

Notice that we mask the value but keep the parameter name, so the log still shows that a key was sent. Personal data in paths, such as an email address used as an id, deserves the same thought; in those cases we log the URI template, such as /users/{email}, rather than the expanded URI.

5Logging Bodies, and What It Costs

Response bodies are streams: they can be read only once, by the caller. To log a body in an interceptor, we would have to read it fully into memory and give the caller a copy, which is what wrapping the request factory in BufferingClientHttpRequestFactory does. That costs memory for every call, can hold megabytes for large responses, and makes the logs a store of personal and business data. So body logging is off by default. If we need it for debugging, we enable it only at DEBUG level for a specific client, cap the logged size, for example the first 2 KB, and apply the same masking to fields such as passwords and card numbers.

6What Micrometer Already Records

With Spring Boot and the actuator, the auto-configured RestClient.Builder is instrumented with Micrometer observation. Every call produces an http.client.requests timer with tags such as method, uri (the URI template, so /stock/{sku} rather than one tag per sku), status, outcome and client.name, and with tracing enabled it creates a span and propagates the trace headers. That means dashboards and alerts for latency and error rate need no custom code, and the URI template keeps metric cardinality low, which is why we should pass templates and variables to uri() rather than concatenated strings.

So the interceptor's job is narrower: a human-readable line per call, correlated with the trace id from the logging context, for the moments when we need to read what happened to one request. Metrics answer "how often and how fast"; the log line answers "what exactly happened to this call".

7Follow-up questions

Should the log line be INFO or DEBUG?

It depends on volume. For a service making a few hundred calls per second, one INFO line per call can dominate log costs. Many teams log failures and slow calls at INFO or WARN, and successful fast calls at DEBUG, which keeps the useful lines and drops the noise.

How do you correlate the log line with a trace?

With Micrometer Tracing configured, Spring Boot puts the trace and span ids into the logging context (MDC), and the standard log patterns print them. The interceptor's line then carries the same trace id as the span for that call, so we can jump from a log line to the full trace.

Could you use an ExchangeFilterFunction instead?

That is the equivalent for WebClient. For RestClient and RestTemplate the extension point is ClientHttpRequestInterceptor. The same rules about masking, bodies and metrics apply to both.

8Conclusion

In this answer, we wrote a ClientHttpRequestInterceptor that measures each RestClient call with System.nanoTime() around execution.execute(request, body) and logs the method, a masked URI, the status and the duration, and logs the exception type on failure. We registered it with requestInterceptor() or a RestClientCustomizer, kept headers out of the logs entirely, masked secret query parameters and user info, left body logging off because buffering costs memory and spreads data, and saw that Micrometer observation already gives us http.client.requests metrics and traces.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write a ClientHttpRequestInterceptor. In intercept, I take System.nanoTime(), call execution.execute(request, body), and then log request.getMethod(), the URI and response.getStatusCode() with the elapsed milliseconds. In a catch for IOException I log the method, URI, the exception type and the duration, and rethrow.

Then, if they want more

I register it with RestClient.builder().requestInterceptor(...), or in Spring Boot with a RestClientCustomizer bean so every client gets it. For secrets, I simply do not log headers, so Authorization, Cookie and API key headers never appear; if I need a header I use an allow-list.

URLs can carry secrets too, so I rebuild the URI with UriComponentsBuilder, drop any user-info part and replace values of parameters like token, api_key or signature with three stars.

I would not log bodies by default, because the body is a stream and logging it means buffering every response with BufferingClientHttpRequestFactory, which costs memory and puts personal data into logs; if needed, only at DEBUG, for one client, with a size cap. Note the duration measures until headers arrive, not the body read.

And Spring Boot already gives us http.client.requests metrics with URI templates and tracing through Micrometer, so the log line is for reading individual calls, correlated by trace id.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Log the method, URL, status and duration of every outgoing call made with Spring's...": https://scrivio-interview-library.netlify.app/spring-boot/http-clients/495292b542/