Skip to content

Commit

Permalink
Hack Timer UX without copying the Builder
Browse files Browse the repository at this point in the history
  • Loading branch information
jonatan-ivanov committed Sep 22, 2023
1 parent 80c20e1 commit d0f934b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,10 @@ public Builder description(String description) {
return super.description(description);
}

public Function<Tags, Timer> with(MeterRegistry registry) {
return extraTags -> register(registry, tags.and(extraTags));
}

/**
* Add the timer to a single registry, or return an existing timer in that
* registry. The returned timer will be unique for each registry, but each
Expand All @@ -439,6 +443,10 @@ public Builder description(String description) {
* @return A new or existing timer.
*/
public Timer register(MeterRegistry registry) {
return register(registry, tags);
}

private Timer register(MeterRegistry registry, Tags tags) {
// the base unit for a timer will be determined by the monitoring system
// implementation
return registry.timer(new Meter.Id(name, tags, null, description, Type.TIMER),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.micrometer.core.samples;

import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.Timer;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;

import java.time.Duration;
import java.util.function.Function;

public class Demo {

private static final PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);

private static final Function<Tags, Timer> timerFactory = Timer.builder("cache.initialization.latency")
.description("Time initialize cache from database")
.tag("static", "abc")
.publishPercentiles(0.99, 0.999)
.publishPercentileHistogram()
.minimumExpectedValue(Duration.ofSeconds(10))
.maximumExpectedValue(Duration.ofSeconds(600))
.with(registry);

public static void main(String[] args) {
doSomething("test");
}

private static void doSomething(String cacheName) {
timerFactory.apply(Tags.of("cacheName", cacheName)).record(Duration.ofMillis(100));
System.out.println(registry.scrape());
}

}

0 comments on commit d0f934b

Please sign in to comment.