spring-bootprometheusgaugemicrometer

How to update MicroMeter gauge according to labels


I use MicroMeter gauges in a Spring Boot 2 application to track statuses of objects. On status change, the statusArrived() method is called. This function should update the gauge related to that object.

Here is my current implementation:

public class PrometheusStatusLogger {

    private int currentStatus;

    public void statusArrived(String id, int value) {
        currentStatus = value;
        Tags tags = Tags.of("product_id", id);

        Gauge.builder("product_status",this::returnStatus)
          .tags(tags)
          .strongReference(true)
          .register(Metrics.globalRegistry);
    }

    private int returnStatus(){
        return currentStatus;
    }    
}

This works quite well, but the problem is that when this method is called, all gauges values are updated. I would like only the gauge with the given product_id to be updated.

Input:

statusArrived(1, 2);
statusArrived(2, 3);


Current output:

product_status{product_id=1} 3
product_status{product_id=2} 3

All gauges are updated

Desired output:

product_status{product_id=1} 2
product_status{product_id=2} 3

Only the gauge with the given product_id tag is updated.

How can I achieve that ?


Solution

  • Since all your gauges are referencing the same currentStatus, when the new value comes in, all the gauge's source is changed. Instead use a map to track all the current status by id:

    public class PrometheusStatusLogger {
    
        private Map<String, Integer> currentStatuses =  new HashMap<>();
    
        public void statusArrived(String id, int value) {
            if(!currentStatuses.containsKey(id)) {
                Tags tags = Tags.of("product_id", id);
                Gauge.builder("product_status",currentStatuses, map -> map.get(id))
                        .tags(tags)
                        .register(Metrics.globalRegistry);
            }
            currentStatuses.put(id, value);
        }
    
    }