Understand how we can add tags in rest template metrics using the default client request observation convention class available in Spring Boot 3. These tags will be added as additional tags on top of the default tags that are provided by the framework.
Context
When we add Spring Boot Starter Actuator dependency in our Spring Boot application, we can access the metrics for our application endpoints via the actuator metrics endpoint. Similarly, if we want to access the metrics for external calls that are performed by our application then we need to send the GET request specifying the name of metrics we are interested in i.e. in our case client requests metrics.
curl --request GET 'http://localhost:8080/actuator/metrics/http.client.requests'
ShellScriptBy default, metrics are available with the name ‘http.client.requests’. This name can be customized by setting one property in the application.properties file.
When we send the request to the above endpoint, by default, we get the following tags in the output:
- method: HTTP method.
- uri: endpoints for which we received the requests
- outcome: whether the request was processed successfully or not
- status: HTTP status code
- clientName: hostname of the URL that we are trying to call
Note:
The client metrics will available only if we have created the RestTemplate bean using the RestTemplateBuilder. If we have created the RestTemplate object using the new RestTemplate(), in that case, client metrics will not be available.
Advantages
Once the custom tags are added, we can utilize this information to create charts and dashboards displaying information at a more granular level.
Example: Consider we have an external service that provides information about the user whether the user is a freemium user or user is a premium user. Based on the output received from this service, we can add our custom tags highlighting the user type. We can utilize this information to create graphs and charts and see the ratio of requests that we are receiving from different types of users.
Adding Custom Tags
Note:
Below mentioned steps works only in case of Spring Boot 3.x. For Spring Boot 2.x, kindly refer to article Spring Boot 2: Add Tags in Rest Template Metrics.
If we want to add our tags in addition to tags that are provided by Spring Framework then we can do it with the help of the Default Client Request Observation Convention.
Steps:
- Create a class that extends the DefaultClientRequestObservationConvention class.
- Override the getLowCardinalityKeyValues method wherein we will call the superclass getLowCardinalityKeyValues method to get the default tags and then we can add our additional tags.
- Register this class as Spring Bean using @Component annotation.
import io.micrometer.common.KeyValue;
import io.micrometer.common.KeyValues;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.observation.ClientRequestObservationContext;
import org.springframework.http.client.observation.DefaultClientRequestObservationConvention;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
/**
* The type Bootcamp to prod extended client request observation convention.
* Useful for adding our own additional tags in rest template metrics
*/
@Component
public class BootcampToProdExtendedClientRequestObservationConvention extends DefaultClientRequestObservationConvention {
// Use constructor only if you want to customize the name of metrics
// Default name will be 'http.client.requests'
/*public BootcampToProdExtendedClientRequestObservationConvention(@Value("${management.observations.http.client.requests.name}") String httpClientRequestsName) {
super(httpClientRequestsName);
}*/
@Override
public KeyValues getLowCardinalityKeyValues(ClientRequestObservationContext context) {
// here, we just want to have an additional KeyValue to the observation, keeping the default values
return super.getLowCardinalityKeyValues(context).and(additionalTags(context));
}
protected KeyValues additionalTags(ClientRequestObservationContext context) {
KeyValues keyValues = KeyValues.empty();
ClientHttpRequest request = context.getCarrier();
String uri = request.getURI().toString();
// Optional tag which will be present in metrics only when the condition is evaluated to true
MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUriString(uri).build().getQueryParams();
if (parameters.containsKey("id")) {
keyValues = keyValues.and(KeyValue.of("userId", parameters.get("id").get(0)));
}
// Custom tag which will be present in all the controller metrics
keyValues = keyValues.and(KeyValue.of("tag", "value"));
return keyValues;
}
}
JavaWe have control over a request object using context.getCarrier(), response object using context.getResponse(), and exception object using context.getError(). Based on this, we can add our own tags.
In the above example, we have added two tags “userId” and “tag” wherein the “userId” tag is optional. It will be added to metrics only if the URL contains the query parameter “id” whereas the “tag” tag will be added to metrics for all the requests that we have sent using the rest template.
Output:
Source Code
The source code for this example can be found on GitHub. Link: click here
Learn More
Curious to Learn Something New?
Check out how we can override the default tags in Spring Boot 3.
Add a Comment