Search This Blog

Monday, October 12, 2020

Micrometer with Dynamic Tags

 With Micrometer, it is easy to create a counter with Builder:

Counter okCounter = Counter.builder("http.status.count")
.tag("status", "200")
.description("The number of OK count")
.register(meterRegistry);
Counter notFoundCounter = Counter.builder("http.status.count")
.tag("status", "404")
.description("The number of not found count")
.register(meterRegistry);

However, it is not feasible to create counter for every HTTP status.  We can use Java HashMap to cache the creation dynamically by leveraging the method computeIfAbsent

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;

public class HttpStatusCounter {
private static final String HTTP_STATUS_COUNT = "http.status.count";
private final MeterRegistry meterRegistry;
private Map<Integer, Counter> httpStatusCounterMap;

public HttpStatusCounter(MeterRegistry meterRegistry) {
httpStatusCounterMap = new ConcurrentHashMap<>();
this.meterRegistry = meterRegistry;
}

public void increment(HttpStatus status, int amount) {
Counter statusCounter = httpStatusCounterMap.computeIfAbsent(
status.value(), k -> Counter.builder(HTTP_STATUS_COUNT)
.tag("status", String.valueOf(status.value()))
.register(meterRegistry));
statusCounter.increment(amount);
}
}