Java Code Examples for io.micrometer.core.instrument.Timer#record()

The following examples show how to use io.micrometer.core.instrument.Timer#record() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenfeignMetricsBinder.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Around("execution(* feign.Client.execute(..))")
public Response around(ProceedingJoinPoint pjp) throws Throwable {
    long start = MicrometerUtil.monotonicTime();
    Request request = (Request)pjp.getArgs()[0];
    Response response = null;
    Throwable e = null;
    try {
        response = (Response)pjp.proceed();
    } catch (Throwable t) {
        throw e = t;
    } finally {
        long lapsed = MicrometerUtil.monotonicTime() - start;
        Timer timer = Metrics.timer("openfeign",
            Tags.of(tags)
                .and(Tag.of("status", null == response ? "CLIENT_ERROR" : String.valueOf(response.status())),
                    Tag.of("method", request.method()), Tag.of("class", getKey(CLASS_HEADER, request.headers())),
                    Tag.of("classMethod", getKey(METHOD_HEADER, request.headers()))
                // Tag.of("url", getUrl(request.url()))
                ).and(MicrometerUtil.exceptionAndStatusKey(e)));
        timer.record(lapsed, TimeUnit.NANOSECONDS);
    }
    return response;
}
 
Example 2
Source File: SpectatorTimerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void timerMax() {
    AtlasConfig atlasConfig = new AtlasConfig() {
        @Override
        public String get(String k) {
            return null;
        }

        @Override
        public Duration lwcStep() {
            return step();
        }
    };
    AtlasMeterRegistry registry = new AtlasMeterRegistry(atlasConfig, new MockClock());
    Timer timer = registry.timer("timer");

    timer.record(1, TimeUnit.SECONDS);
    clock(registry).add(atlasConfig.step());
    assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(1000);
}
 
Example 3
Source File: SkywalkingTimerTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleTimer() {
    // Creating a simplify timer
    final SkywalkingMeterRegistry registry = new SkywalkingMeterRegistry();
    final Timer timer = registry.timer("test_simple_timer", "skywalking", "test");

    // Check Skywalking type
    Assert.assertTrue(timer instanceof SkywalkingTimer);
    final List<MeterId.Tag> tags = Arrays.asList(new MeterId.Tag("skywalking", "test"));

    // Multiple record data
    timer.record(10, TimeUnit.MILLISECONDS);
    timer.record(20, TimeUnit.MILLISECONDS);
    timer.record(3, TimeUnit.MILLISECONDS);

    // Check micrometer data
    Assert.assertEquals(3, timer.count());
    Assert.assertEquals(33d, timer.totalTime(TimeUnit.MILLISECONDS), 0.0);
    Assert.assertEquals(20d, timer.max(TimeUnit.MILLISECONDS), 0.0);

    // Check Skywalking data
    assertCounter(Whitebox.getInternalState(timer, "counter"), "test_simple_timer_count", tags, 3d);
    assertCounter(Whitebox.getInternalState(timer, "sum"), "test_simple_timer_sum", tags, 33d);
    assertGauge(Whitebox.getInternalState(timer, "max"), "test_simple_timer_max", tags, 20d);
    assertHistogramNull(Whitebox.getInternalState(timer, "histogram"));
}
 
Example 4
Source File: SimpleMeterRegistryTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Issue("#370")
@Test
void serviceLevelObjectivesOnlyNoPercentileHistogram() {
    DistributionSummary summary = DistributionSummary.builder("my.summary")
            .serviceLevelObjectives(1.0, 2)
            .register(registry);

    summary.record(1);

    Timer timer = Timer.builder("my.timer").serviceLevelObjectives(Duration.ofMillis(1)).register(registry);
    timer.record(1, TimeUnit.MILLISECONDS);

    Gauge summaryHist1 = registry.get("my.summary.histogram").tags("le", "1").gauge();
    Gauge summaryHist2 = registry.get("my.summary.histogram").tags("le", "2").gauge();
    Gauge timerHist = registry.get("my.timer.histogram").tags("le", "0.001").gauge();

    assertThat(summaryHist1.value()).isEqualTo(1);
    assertThat(summaryHist2.value()).isEqualTo(1);
    assertThat(timerHist.value()).isEqualTo(1);

    clock.add(SimpleConfig.DEFAULT.step());

    assertThat(summaryHist1.value()).isEqualTo(0);
    assertThat(summaryHist2.value()).isEqualTo(0);
    assertThat(timerHist.value()).isEqualTo(0);
}
 
Example 5
Source File: MicrometerAtlasIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTimer_whenEnrichWithQuantile_thenQuantilesComputed() {
    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    Timer timer = Timer
      .builder("test.timer")
      .quantiles(WindowSketchQuantiles
        .quantiles(0.3, 0.5, 0.95)
        .create())
      .register(registry);

    timer.record(2, TimeUnit.SECONDS);
    timer.record(2, TimeUnit.SECONDS);
    timer.record(3, TimeUnit.SECONDS);
    timer.record(4, TimeUnit.SECONDS);
    timer.record(8, TimeUnit.SECONDS);
    timer.record(13, TimeUnit.SECONDS);

    Map<String, Integer> quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9);
    assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8)));
}
 
Example 6
Source File: TimerTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("record supplier")
default void recordWithSupplier(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    String expectedResult = "response";
    Supplier<String> supplier = () -> {
        clock(registry).add(10, TimeUnit.NANOSECONDS);
        return expectedResult;
    };
    try {
        String supplierResult = t.record(supplier);
        assertEquals(expectedResult, supplierResult);
        clock(registry).add(step());
    } finally {
        assertAll(() -> assertEquals(1L, t.count()),
                () -> assertEquals(10, t.totalTime(TimeUnit.NANOSECONDS), 1.0e-12));
    }
}
 
Example 7
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("zero times contribute to the count of overall events but do not add to total time")
default void recordZero(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(0, TimeUnit.MILLISECONDS);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(0L, t.totalTime(TimeUnit.NANOSECONDS)));
}
 
Example 8
Source File: SkywalkingTimerTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuilder() {
    // Creating a support histogram timer
    final SkywalkingMeterRegistry registry = new SkywalkingMeterRegistry();
    Timer timer = Timer.builder("test_complex_timer")
        .tag("skywalking", "test")
        .publishPercentiles(0.5, 0.95) // median and 95th percentile
        .serviceLevelObjectives(Duration.ofMillis(10), Duration.ofMillis(20))
        .minimumExpectedValue(Duration.ofMillis(1))
        .register(registry);

    // Check Skywalking type
    Assert.assertTrue(timer instanceof SkywalkingTimer);
    final List<MeterId.Tag> tags = Arrays.asList(new MeterId.Tag("skywalking", "test"));

    // Multiple record data
    timer.record(10, TimeUnit.MILLISECONDS);
    timer.record(22, TimeUnit.MILLISECONDS);
    timer.record(13, TimeUnit.MILLISECONDS);

    // Check micrometer data
    Assert.assertEquals(3, timer.count());
    Assert.assertEquals(45d, timer.totalTime(TimeUnit.MILLISECONDS), 0.0);
    Assert.assertEquals(22d, timer.max(TimeUnit.MILLISECONDS), 0.0);

    // Check Skywalking data
    assertCounter(Whitebox.getInternalState(timer, "counter"), "test_complex_timer_count", tags, 3d);
    assertCounter(Whitebox.getInternalState(timer, "sum"), "test_complex_timer_sum", tags, 45d);
    assertGauge(Whitebox.getInternalState(timer, "max"), "test_complex_timer_max", tags, 22d);
    assertHistogram(Whitebox.getInternalState(timer, "histogram"), "test_complex_timer_histogram", tags, 1, 0, 10, 2, 20, 1);
}
 
Example 9
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Deprecated
@Test
default void histogramCounts(MeterRegistry registry) {
    Timer t = Timer.builder("my.timer")
            .serviceLevelObjectives(Duration.ofMillis(1))
            .register(registry);

    t.record(1, TimeUnit.MILLISECONDS);
    assertThat(t.histogramCountAtValue((long) millisToUnit(1, TimeUnit.NANOSECONDS))).isEqualTo(1);
    assertThat(t.histogramCountAtValue(1)).isNaN();
}
 
Example 10
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Deprecated
@Test
default void percentiles(MeterRegistry registry) {
    Timer t = Timer.builder("my.timer")
            .publishPercentiles(1)
            .register(registry);

    t.record(1, TimeUnit.MILLISECONDS);
    assertThat(t.percentile(1, TimeUnit.MILLISECONDS)).isEqualTo(1, Offset.offset(0.3));
    assertThat(t.percentile(0.5, TimeUnit.MILLISECONDS)).isNaN();
}
 
Example 11
Source File: MicrometerChannelMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void recordConnectTime(SocketAddress remoteAddress, Duration time, String status) {
	String address = reactor.netty.Metrics.formatSocketAddress(remoteAddress);
	Timer timer = connectTimeCache.computeIfAbsent(new MeterKey(null, address, null, status),
			key -> filter(connectTimeBuilder.tags(REMOTE_ADDRESS, address, STATUS, status)
			                                .register(REGISTRY)));
	if (timer != null) {
		timer.record(time);
	}
}
 
Example 12
Source File: DropwizardMeterRegistriesTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void unwantedGaugesAreFilteredOut() {
    final DropwizardMeterRegistry micrometer = DropwizardMeterRegistries.newRegistry();
    final MetricRegistry dropwizard = micrometer.getDropwizardRegistry();

    final DistributionSummary percentileSummary = DistributionSummary.builder("percentileSummary")
                                                                     .publishPercentiles(0.5, 0.99)
                                                                     .register(micrometer);
    final DistributionSummary histogramSummary = DistributionSummary.builder("histogramSummary")
                                                                    .sla(10, 100)
                                                                    .register(micrometer);
    final Timer percentileTimer = Timer.builder("percentileTimer")
                                       .publishPercentiles(0.5, 0.99)
                                       .register(micrometer);
    final Timer histogramTimer = Timer.builder("histogramTimer")
                                      .sla(Duration.ofSeconds(10), Duration.ofSeconds(100))
                                      .register(micrometer);
    percentileSummary.record(42);
    histogramSummary.record(42);
    percentileTimer.record(42, TimeUnit.SECONDS);
    histogramTimer.record(42, TimeUnit.SECONDS);

    final Map<String, Double> measurements = MoreMeters.measureAll(micrometer);
    measurements.forEach((key, value) -> assertThat(key).doesNotContain(".percentile")
                                                        .doesNotContain(".histogram")
                                                        .doesNotContain("phi=")
                                                        .doesNotContain("le="));

    // Must be exported as 2 Histograms and 2 Timers only.
    assertThat(dropwizard.getHistograms()).hasSize(2);
    assertThat(dropwizard.getTimers()).hasSize(2);
}
 
Example 13
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("record durations")
default void recordDuration(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(Duration.ofMillis(42));
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(42, t.totalTime(TimeUnit.MILLISECONDS), 1.0e-12));
}
 
Example 14
Source File: TimerTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("total time and count are preserved for a single timing")
default void record(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(42, TimeUnit.MILLISECONDS);
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
            () -> assertEquals(42, t.totalTime(TimeUnit.MILLISECONDS), 1.0e-12));
}
 
Example 15
Source File: MicrometerHttpClientMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void recordDataSentTime(SocketAddress remoteAddress, String uri, String method, Duration time) {
	String address = Metrics.formatSocketAddress(remoteAddress);
	Timer dataSentTime = dataSentTimeCache.computeIfAbsent(new MeterKey(uri, address, method, null),
			key -> filter(dataSentTimeBuilder.tags(REMOTE_ADDRESS, address, URI, uri, METHOD, method)
			                                 .register(REGISTRY)));
	if (dataSentTime != null) {
		dataSentTime.record(time);
	}
}
 
Example 16
Source File: MicrometerHttpServerMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void recordResponseTime(String uri, String method, String status, Duration time) {
	Timer responseTime = responseTimeCache.computeIfAbsent(new MeterKey(uri, null, method, status),
			key -> filter(responseTimeBuilder.tags(URI, uri, METHOD, method, STATUS, status)
			                                 .register(REGISTRY)));
	if (responseTime != null) {
		responseTime.record(time);
	}
}
 
Example 17
Source File: DistributionSummaryTest.java    From pepper-metrics with Apache License 2.0 4 votes vote down vote up
@Test
    public void test() throws InterruptedException {
        final PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
        final Timer summary = Timer.builder("test")
                .distributionStatisticExpiry(Duration.ofSeconds(10))
                .publishPercentiles(0.9D, 0.99D, 0.999D)
                .distributionStatisticBufferLength(20)
                .publishPercentileHistogram(false)
                .tags(new String[]{"method", "get()"})
                .register(prometheusRegistry);
//        final DistributionSummary summary = DistributionSummary.builder("test")
//                .distributionStatisticExpiry(Duration.ofSeconds(30))
//                .publishPercentiles(0.9, 0.99, 0.999)
//                .publishPercentileHistogram(false)
//                .tags(new String[]{"method", "get()"})
//                .register(prometheusRegistry);
        AtomicInteger second = new AtomicInteger();
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
            final HistogramSnapshot snapshot = summary.takeSnapshot();
            final ValueAtPercentile[] valueAtPercentiles = snapshot.percentileValues();
            double p90 = 0, p99 = 0, p999 = 0;
            for (ValueAtPercentile percentile : valueAtPercentiles) {
                if (percentile.percentile() == 0.9D) {
                    p90 = percentile.value(TimeUnit.MILLISECONDS);
                } else if (percentile.percentile() == 0.99D) {
                    p99 = percentile.value(TimeUnit.MILLISECONDS);
                } else {
                    p999 = percentile.value(TimeUnit.MILLISECONDS);
                }
            }
            System.out.println(String.format("second: %s, p90: %s, p99: %s, p999: %s", second.incrementAndGet(), p90, p99, p999));
        }, 1, 1, TimeUnit.SECONDS);
        for (int j = 0; j < 100; j++) {
//            for (long i = 0; i < 1000; i++) {
//                summary.record(i, TimeUnit.MILLISECONDS);
//            }
            summary.record(j % 10, TimeUnit.MILLISECONDS);
            TimeUnit.SECONDS.sleep(1);
        }

        for (int i = 0; i < 10; i++) {
            TimeUnit.SECONDS.sleep(1);
        }

        for (int i = 0; i < 100; i++) {
            TimeUnit.SECONDS.sleep(1);
        }
    }
 
Example 18
Source File: Timers.java    From vertx-micrometer-metrics with Apache License 2.0 4 votes vote down vote up
public void end(String... values) {
  Timer t = ref.get(values);
  t.record(System.nanoTime() - nanoStart, TimeUnit.NANOSECONDS);
}
 
Example 19
Source File: MicrometerMetricsReporter.java    From java-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public void reportSpan(SpanData spanData) {
    boolean skip = Arrays.stream(this.metricLabels).anyMatch(m -> m.value(spanData) == null);
    if (skip) {
        return;
    }

    List<Tag> tags = Arrays.stream(this.metricLabels)
        .map(m -> new ImmutableTag(m.name(), m.value(spanData).toString()))
        .collect(Collectors.toList());

    Timer timer = this.registry.find(this.name).tags(tags).timer();
    if (null != timer) {
        // we have a metric registered already, just record the timing:
        timer.record(spanData.getDuration(), TimeUnit.MICROSECONDS);
        return;
    }

    // would be awesome if we could reuse the builder, but looks like we can't, as we can't override the name
    Timer.Builder builder = Timer.builder(this.name).tags(tags);
    if (publishPercentileHistogram) {
        builder.publishPercentileHistogram();
    }

    if (null != percentiles) {
        builder.publishPercentiles(percentiles);
    }

    if (null != sla) {
        builder.sla(sla);
    }

    if (null != minimumExpectedValue) {
        builder.minimumExpectedValue(minimumExpectedValue);
    }

    if (null != maximumExpectedValue) {
        builder.maximumExpectedValue(maximumExpectedValue);
    }

    builder.register(this.registry).record(spanData.getDuration(), TimeUnit.MICROSECONDS);
}
 
Example 20
Source File: RestBotEngine.java    From EDDI with Apache License 2.0 4 votes vote down vote up
private static void record(long startTime, Timer timer) {
    timer.record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}