admin管理员组

文章数量:1122832

I am trying to add a custom tag to the http.client.requests WebClient metrics that are provided by Spring Boot. I have a value that I have placed in the MDC which I want to use for this custom tag. My service code where I make the WebClient call looks similar to the following:

void makeWebClientCall() {

    String customValue;

    ...
    ...
    
    MDC.put("customKey", customValue);

    webClient.post()
    .uri(partnerUrl)
    .retrieve()
    .bodyToMono(Void.class)
    .block();
}


Then, for adding the custom tag, I have followed this section of the Spring documentation, and this is what my I have in my configuration class:

class ExtendedWebClientRequestObservationConvention extends DefaultClientRequestObservationConvention {

    @Override
    public KeyValues getLowCardinalityKeyValues(ClientRequestObservationContext context) {

        return super.getLowCardinalityKeyValues(context).and(customValue());
    }

    private KeyValue customValue() {

        var customValue = Optional.ofNullable(MDC.get("customKey"))
                .orElse(NONE_VALUE);

        return KeyValue.of("customKey", customValue);
    }

}

But what I observe when I make web client calls and then retrieve metrics from the actuator/prometheus endpoint is that "customKey" metric's tag value is always set to "none" and not "customValue" like so:

http_client_requests_seconds_max{...method="POST",outcome="SUCCESS",status="200",customKey="none"...}

And when I debug the ExtendedWebClientRequestObservationConvention code, I see that MDC.get("customKey") is returning null. So maybe what is happening is that when micrometer is creating the observation for the metric, it is happening in a new thread where the MDC does not have that value set?

How can I copy the MDC to the thread where micrometer is creating the observation? Or is there a way for me to set the custom tags without using the MDC, is there somewhere in the WebClient call where I can pass this custom tag value?

本文标签: spring bootCustom WebClient Metrics Tag From The MDCStack Overflow