'Add custom labels to default spring boot actuator metrics

I'm currently working on a Spring boot (webflux) project where we have exposed metrics of our application on /actuator/prometheus endpoint using spring boot actuator dependency which by default gave us for example: http_server_requests_seconds_bucket metric. By default it has {exception="None",method="POST",outcome="SUCCESS",status="200",uri="/test",le="0.268435456",} labels. I want to add another label say "challenge" which depends on the request payload. For example, my request payload looks like this,

{
 "type" : "basic",
 "method" : "someMethod"
}

I want to add a label within that metric as, http_server_requests_seconds_bucket{exception="None",...,challenge="basic"} which is based on the request payload "type" parameter. Can someone tell me how can I add custom label to the existing default metric provided by spring-boot-actuator

Note: We only have limited number of values for "type" so that it doesn't explode



Solution 1:[1]

After a bit of research I found we can do this by extending a class called DefaultWebMvcTagsProvider (for Spring MVC) and adding custom tag.

@Component
public class CustomTagsAdder extends DefaultWebMvcTagsProvider {

@Override
public Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler, Throwable exception) {

    List<Tag> tags = new ArrayList<>();
    tags.add(Tag.of("CUSTOM_TAG_KEY", "CUSTOM_TAG_VALUE")); // Repeat this line for each of the tags you want


    for(Tag tag : super.getTags(request, response, handler, exception))
        tags.add(tag);

    return tags;
}
}

Similarly for webflux projects you can extend DefaultWebFluxTagsProvider and add your custom tags.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JustAnotherDev