Prometheus Spring boot custom metric

Creating Custom Metrics in Spring Boot using Micrometer API

I would like to create a custom metric in Spring Boot application using Micrometer API. So that it can be exposed to any supported monitoring tool like Prometheus/Wavefront etc.,

In this example, we are going to create a Counter type metric in Spring PetClinic application. I would like to Count the number of Pets created by Pet Type.

Initialize the Counter object

In the below example, we are creating a metric object using fluent builder API. Creating multiple counter objects, one per pet type.

import io.micrometer.core.instrument.MeterRegistry;

class PetResource {
    
    ...
	private Map<Integer, Counter> metricCounters = null;
    private MeterRegistry meterRegistry;
    
    ...
    
        @Autowired
    public PetResource(MeterRegistry meterRegistry, PetRepository petRepository, OwnerRepository ownerRepository) {
        this.meterRegistry = meterRegistry;
        this.petRepository = petRepository;
        this.ownerRepository = ownerRepository;
        initPetCounters();
    }
    
    ...
        
    private void initPetCounters() {
        List<PetType> petTypes = this.getPetTypes();
        metricCounters = new HashMap<Integer, Counter>();

        for (PetType petType : petTypes) {
            Counter petCounter = Counter.builder("pets.by.type")
                                    .tag("type", petType.getName())
                                    .description("Number of Pets created by type")
                                    .register(meterRegistry); //Create counter by fluent API.
             metricCounters.put(petType.getId(), petCounter);
            
            //this.meterRegistry.counter("pets.by.type", "type", "cat"); // Sample create metric without fluent API
        }
    }
}

Increment the Counter on new Pet Creation

Based on the type of the Pet created, will increment the counter (default by 1).

...
class PetResource {
    
    ...
    public Pet processCreationForm( ... ) {
        ...
        Counter counter = metricCounters.get(petRequest.getTypeId());
        counter.increment();
        ...
    }
        
    ...
    
}

Once you deploy your application and enable Prometheus metrics, when you create a new Pet, you will see the below new metrics in Prometheus url (/actuator/prometheus).

# HELP pets_by_type_total Number of Pets created by type
# TYPE pets_by_type_total counter
pets_by_type_total{type="cat",} 1.0
pets_by_type_total{type="hamster",} 0.0
pets_by_type_total{type="bird",} 1.0
pets_by_type_total{type="snake",} 0.0
pets_by_type_total{type="dog",} 0.0
pets_by_type_total{type="lizard",} 0.0

The completed code is available in the Github repo in k8s-no-wavefront branch. Here is the link for the class.

39
Total Page Visits: 8954 - Today Page Visits: 17

Leave a Reply

Your email address will not be published.