org.eclipse.microprofile.metrics.Histogram Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.Histogram. 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: HistogramTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricRegistry() throws Exception {
    String histogramIntName = "org.eclipse.microprofile.metrics.tck.metrics.HistogramTest.histogramInt";
    String histogramLongName = "test.longData.histogram";

    MetricID histogramIntNameMetricID = new MetricID(histogramIntName);
    MetricID histogramLongNameMetricID = new MetricID(histogramLongName);

    Histogram histogramInt = metrics.getHistogram(histogramIntNameMetricID);
    Histogram histogramLong = metrics.getHistogram(histogramLongNameMetricID);

    assertThat("Histogram is not registered correctly", histogramInt, notNullValue());
    assertThat("Histogram is not registered correctly", histogramLong, notNullValue());

    TestUtils.assertEqualsWithTolerance(48, histogramInt.getSnapshot().getValue(0.5));
    TestUtils.assertEqualsWithTolerance(480, histogramLong.getSnapshot().getValue(0.5));
}
 
Example #2
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private MetricType metricTypeFromClass(Class<?> in) {
    if (in.equals(Counter.class)) {
        return MetricType.COUNTER;
    } else if (in.equals(Gauge.class)) {
        return MetricType.GAUGE;
    } else if (in.equals(ConcurrentGauge.class)) {
        return MetricType.CONCURRENT_GAUGE;
    } else if (in.equals(Meter.class)) {
        return MetricType.METERED;
    } else if (in.equals(Timer.class)) {
        return MetricType.TIMER;
    } else if (in.equals(SimpleTimer.class)) {
        return MetricType.SIMPLE_TIMER;
    } else if (in.equals(Histogram.class)) {
        return MetricType.HISTOGRAM;
    }
    return null;
}
 
Example #3
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private boolean isSameType(Metric metricInstance, MetricType type) {
    switch (type) {
        case CONCURRENT_GAUGE:
            return metricInstance instanceof ConcurrentGauge;
        case GAUGE:
            return metricInstance instanceof Gauge;
        case HISTOGRAM:
            return metricInstance instanceof Histogram;
        case TIMER:
            return metricInstance instanceof Timer;
        case METERED:
            return metricInstance instanceof Meter;
        case COUNTER:
            return metricInstance instanceof Counter;
        case SIMPLE_TIMER:
            return metricInstance instanceof SimpleTimer;
        default:
            throw new IllegalArgumentException();
    }
}
 
Example #4
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Histogram with unit=MINUTES,
 * check that the statistics from OpenMetricsExporter will be presented in SECONDS.
 */
@Test
public void histogram_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("histogram1")
            .withType(MetricType.HISTOGRAM)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Histogram metric = registry.histogram(metadata);
    metric.update(30);
    metric.update(40);
    metric.update(50);

    OpenMetricsExporter exporter = new OpenMetricsExporter();
    String exported = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("histogram1")).toString();

    Assert.assertThat(exported, containsString("application_histogram1_min_seconds 1800.0"));
    Assert.assertThat(exported, containsString("application_histogram1_max_seconds 3000.0"));
    Assert.assertThat(exported, containsString("application_histogram1_mean_seconds 2400.0"));
    Assert.assertThat(exported, containsString("application_histogram1_seconds{quantile=\"0.5\"} 2400.0"));
}
 
Example #5
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Histogram with unit=dollars (custom unit),
 * check that the statistics from OpenMetricsExporter will be presented in dollars.
 */
@Test
public void histogram_customunit_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("histogram1")
            .withType(MetricType.HISTOGRAM)
            .withUnit("dollars")
            .build();
    Histogram metric = registry.histogram(metadata);
    metric.update(30);
    metric.update(40);
    metric.update(50);

    OpenMetricsExporter exporter = new OpenMetricsExporter();
    String exported = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("histogram1")).toString();

    Assert.assertThat(exported, containsString("application_histogram1_min_dollars 30.0"));
    Assert.assertThat(exported, containsString("application_histogram1_max_dollars 50.0"));
    Assert.assertThat(exported, containsString("application_histogram1_mean_dollars 40.0"));
    Assert.assertThat(exported, containsString("application_histogram1_dollars{quantile=\"0.5\"} 40.0"));
}
 
Example #6
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentHistogramImplementations() {

    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    // the export should behave identical for any class derived from Histogram
    Histogram[] histograms = { new HistogramImpl(new ExponentiallyDecayingReservoir()), new SomeHistogram() };
    int idx = 0;
    for (Histogram h : histograms) {
        String name = "histo_" + idx++;
        applicationRegistry.register(name, h);
        String out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name)).toString();
        String expectedLine = "application_" + name + "_mean 0.0";
        assertThat(out, containsString(expectedLine));
    }
}
 
Example #7
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentHistogramImplementations() {

    JsonExporter exporter = new JsonExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    // the export should behave identical for any class derived from Histogram
    Histogram[] histograms = { new HistogramImpl(new ExponentiallyDecayingReservoir()), new SomeHistogram() };
    int idx = 0;
    for (Histogram h : histograms) {
        String name = "histo_" + idx++;
        applicationRegistry.register(name, h);
        StringBuilder out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name));
        assertNotNull(out);
        System.out.println(out.toString());
        List<String> lines = Arrays.asList(out.toString().split(LINE_SEPARATOR));
        assertEquals(1, lines.stream().filter(line -> line.contains("\"" + name + "\"")).count());
        assertEquals(1, lines.stream().filter(line -> line.contains("\"count\": 0")).count());
    }
}
 
Example #8
Source File: MetricRegistryTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void registerTest() {
    metrics.register("regCountTemp", countTemp);
    assertExists(Counter.class, new MetricID("regCountTemp"));

    metrics.register("regHistoTemp", histoTemp);
    assertExists(Histogram.class, new MetricID("regHistoTemp"));

    metrics.register("regTimerTemp", timerTemp);
    assertExists(Timer.class, new MetricID("regTimerTemp"));

    metrics.register("regSimpleTimerTemp", simpleTimerTemp);
    assertExists(SimpleTimer.class, new MetricID("regSimpleTimerTemp"));

    metrics.register("regConcurrentGaugeTemp", concurrentGaugeTemp);
    assertExists(ConcurrentGauge.class, new MetricID("regConcurrentGaugeTemp"));

    metrics.register("regMeterTemp", meterTemp);
    assertExists(Meter.class, new MetricID("regMeterTemp"));
}
 
Example #9
Source File: TagsTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(6)
public void histogramTagsTest() {
    
    Tag tagEarth = new Tag("planet", "earth");
    Tag tagRed = new Tag("colour", "red");
    Tag tagBlue = new Tag("colour", "blue");
    
    String histogramName = "org.eclipse.microprofile.metrics.tck.TagTest.histogramColour";
    
    Histogram histogramColour = registry.histogram(histogramName);
    Histogram histogramRed = registry.histogram(histogramName,tagEarth,tagRed);
    Histogram histogramBlue = registry.histogram(histogramName,tagEarth,tagBlue);
    
    MetricID histogramColourMID = new MetricID(histogramName);
    MetricID histogramRedMID = new MetricID(histogramName, tagEarth,tagRed);
    MetricID histogramBlueMID = new MetricID(histogramName, tagEarth,tagBlue);
    
    //check multi-dimensional metrics are registered
    assertThat("Histogram is not registered correctly", registry.getHistogram(histogramColourMID), notNullValue());
    assertThat("Histogram is not registered correctly", registry.getHistogram(histogramRedMID), notNullValue());
    assertThat("Histogram is not registered correctly", registry.getHistogram(histogramBlueMID), notNullValue());
}
 
Example #10
Source File: HistogramTagFieldBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void updateHistogramTagField() {
    Histogram histogramOne = registry.getHistogram(histogramOneMID);
    Histogram histogramTwo = registry.getHistogram(histogramTwoMID);
    assertThat("Histogram is not registered correctly", histogramOne, notNullValue());
    assertThat("Histogram is not registered correctly", histogramTwo, notNullValue());
    
    
    // Call the update method and assert the histogram is up-to-date
    long value = Math.round(Math.random() * Long.MAX_VALUE);
    bean.updateOne(value);
    long valueTwo = Math.round(Math.random() * Long.MAX_VALUE);
    bean.updateTwo(valueTwo);
    
    assertThat("Histogram count is incorrect", histogramOne.getCount(), is(equalTo(1L)));
    assertThat("Histogram size is incorrect", histogramOne.getSnapshot().size(), is(equalTo(1)));
    assertThat("Histogram min value is incorrect", histogramOne.getSnapshot().getMin(), is(equalTo(value)));
    assertThat("Histogram max value is incorrect", histogramOne.getSnapshot().getMax(), is(equalTo(value)));
    

    assertThat("Histogram count is incorrect", histogramTwo.getCount(), is(equalTo(1L)));
    assertThat("Histogram size is incorrect", histogramTwo.getSnapshot().size(), is(equalTo(1)));
    assertThat("Histogram min value is incorrect", histogramTwo.getSnapshot().getMin(), is(equalTo(valueTwo)));
    assertThat("Histogram max value is incorrect", histogramTwo.getSnapshot().getMax(), is(equalTo(valueTwo)));
}
 
Example #11
Source File: MetricAppBean.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
public void histogramMe() {

        Metadata metadata = Metadata.builder().withName("metricTest.test1.histogram")
                .withType(MetricType.HISTOGRAM).withUnit(MetricUnits.BYTES).build();
        Histogram histogram = metrics.histogram(metadata);

        // Go both ways to minimize error due to decay
        for (int i = 0; i < 500; i++) {
            histogram.update(i);
            histogram.update(999 - i);
        }

        Metadata metadata2 = Metadata.builder().withName("metricTest.test1.histogram2")
                .withType(MetricType.HISTOGRAM).withUnit(MetricUnits.NONE).build();
        Histogram histogram2 = metrics.histogram(metadata2);
        histogram2.update(1);
    }
 
Example #12
Source File: TimeoutMetricTest.java    From microprofile-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testTimeoutHistogram() {
    MetricGetter m = new MetricGetter(TimeoutMetricBean.class, "histogramTestWorkForMillis");

    timeoutBean.histogramTestWorkForMillis(getConfig().getTimeoutInMillis(300));
    expectTimeout(() -> timeoutBean.histogramTestWorkForMillis(getConfig().getTimeoutInMillis(5000))); // Will timeout after 2000

    Histogram histogram = m.getTimeoutExecutionDuration().get();
    Snapshot snapshot = histogram.getSnapshot();
    List<Long> values = Arrays.stream(snapshot.getValues()).boxed().sorted().collect(toList());

    assertThat("Histogram count", histogram.getCount(), is(2L));
    assertThat("SnapshotValues", values, contains(MetricComparator.approxMillis(300),
                                                  MetricComparator.approxMillis(2000)));
}
 
Example #13
Source File: HistogramFieldBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(2)
public void updateHistogramField() {
    Histogram histogram = registry.getHistogram(histogramMID);
    assertThat("Histogram is not registered correctly", histogram, notNullValue());

    // Call the update method and assert the histogram is up-to-date
    long value = Math.round(Math.random() * Long.MAX_VALUE);
    bean.update(value);
    assertThat("Histogram count is incorrect", histogram.getCount(), is(equalTo(1L)));
    assertThat("Histogram size is incorrect", histogram.getSnapshot().size(), is(equalTo(1)));
    assertThat("Histogram min value is incorrect", histogram.getSnapshot().getMin(), is(equalTo(value)));
    assertThat("Histogram max value is incorrect", histogram.getSnapshot().getMax(), is(equalTo(value)));
}
 
Example #14
Source File: MetadataMismatchTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void metricsWithSameTypeAndMetadata() {
    Metadata metadata1 = Metadata.builder().withName("myhistogram").withDescription("description1").build();
    Metadata metadata2 = Metadata.builder().withName("myhistogram").withDescription("description1").build();

    Histogram histogram1 = registry.histogram(metadata1);
    Histogram histogram2 = registry.histogram(metadata2);

    assertEquals(histogram1, histogram2);
    assertEquals(1, registry.getMetrics().size());
}
 
Example #15
Source File: MetadataMismatchTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void reusingMetadata() {
    Metadata metadata1 = Metadata.builder().withName("myhistogram").withDescription("description1").build();

    Histogram histogram1 = registry.histogram(metadata1);
    Histogram histogram2 = registry.histogram("myhistogram", new Tag("color", "blue"));

    assertNotEquals(histogram1, histogram2);
    assertEquals(2, registry.getMetrics().size());
    assertThat(registry.getMetadata().get("myhistogram").description().get(), equalTo("description1"));
}
 
Example #16
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private Map<String, JsonValue> exportHistogram(Histogram histogram, String tags) {
    Map<String, JsonValue> map = new HashMap<>();
    map.put("count" + tags, JsonProviderHolder.get().createValue(histogram.getCount()));
    snapshotValues(histogram.getSnapshot(), tags)
            .forEach((map::put));
    return map;
}
 
Example #17
Source File: WeatherService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Path("/histogram")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Histogram getTemperatures() {
    Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F");
    metadata.setDescription("A histogram of recent New York temperatures.");
    histogram = registry.histogram(metadata);
    for(int temp : RECENT_NEW_YORK_TEMPS) {
        histogram.update(temp);
    }
    return histogram;
}
 
Example #18
Source File: MetricsCollectorFactory.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
private Histogram histogramOf(String name) {
    MetricID metricID = new MetricID(name);
    Histogram histogram = registry.getHistograms().get(metricID);
    if (histogram == null) {
        synchronized (operation) {
            histogram = registry.getHistograms().get(metricID);
            if (histogram == null) {
                histogram = registry.histogram(metadataOf(name, MetricType.HISTOGRAM));
            }
        }
    }
    return histogram;
}
 
Example #19
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Histogram histogram(Metadata metadata) {
    return get(new MetricID(metadata.getName()), sanitizeMetadata(metadata, MetricType.HISTOGRAM));
}
 
Example #20
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public Histogram histogram(String name, Tag... tags) {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #21
Source File: MetricGetter.java    From microprofile-fault-tolerance with Apache License 2.0 4 votes vote down vote up
public Optional<Histogram> getBulkheadWaitingDuration() {
    return getMetric(getMetricId(MetricDefinition.BULKHEAD_WAITING_DURATION), Histogram.class);
}
 
Example #22
Source File: MetricGetter.java    From microprofile-fault-tolerance with Apache License 2.0 4 votes vote down vote up
public Optional<Histogram> getBulkheadRunningDuration() {
    return getMetric(getMetricId(MetricDefinition.BULKHEAD_RUNNING_DURATION), Histogram.class);
}
 
Example #23
Source File: MetricGetter.java    From microprofile-fault-tolerance with Apache License 2.0 4 votes vote down vote up
public Optional<Histogram> getTimeoutExecutionDuration() {
    return getMetric(getMetricId(MetricDefinition.TIMEOUT_EXECUTION_DURATION), Histogram.class);
}
 
Example #24
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public Histogram histogram(Metadata metadata) {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #25
Source File: BulkheadMetricTest.java    From microprofile-fault-tolerance with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void bulkheadMetricHistogramTest() throws InterruptedException, ExecutionException, TimeoutException {
    MetricGetter m = new MetricGetter(BulkheadMetricBean.class, "waitForHistogram");
    m.baselineMetrics();
    
    CompletableFuture<Void> waitingFuture = newWaitingFuture();
    
    Future<?> f1 = async.run(() -> bulkheadBean.waitForHistogram(waitingFuture));
    Future<?> f2 = async.run(() -> bulkheadBean.waitForHistogram(waitingFuture));
    bulkheadBean.waitForRunningExecutions(2);
    Future<?> f3 = async.run(() -> bulkheadBean.waitForHistogram(waitingFuture));

    expectBulkheadException(f3);
    
    Thread.sleep(config.getTimeoutInMillis(1000));
    
    waitingFuture.complete(null);
    f1.get(1, MINUTES);
    f2.get(1, MINUTES);
    
    Histogram executionTimes = m.getBulkheadRunningDuration().get();
    Snapshot snap = executionTimes.getSnapshot();
    
    assertThat("histogram count", executionTimes.getCount(), is(2L)); // Rejected executions not recorded in histogram
    assertThat("median", Math.round(snap.getMedian()), approxMillis(1000));
    assertThat("mean", Math.round(snap.getMean()), approxMillis(1000));
    
    // Now let's put some quick results through the bulkhead
    bulkheadBean.waitForHistogram(CompletableFuture.completedFuture(null));
    bulkheadBean.waitForHistogram(CompletableFuture.completedFuture(null));
    
    // Should have 4 results, ~0ms * 2 and ~1000ms * 2
    snap = executionTimes.getSnapshot();
    assertThat("histogram count", executionTimes.getCount(), is(4L));
    List<Long> values = Arrays.stream(snap.getValues()).sorted().boxed().collect(toList());
    assertThat("histogram values", values, contains(lessThanMillis(500),
                                                    lessThanMillis(500),
                                                    approxMillis(1000),
                                                    approxMillis(1000)));
}
 
Example #26
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public Histogram histogram(Metadata metadata, Tag... tags) {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #27
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public SortedMap<MetricID, Histogram> getHistograms() {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #28
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public SortedMap<MetricID, Histogram> getHistograms(MetricFilter filter) {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #29
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Histogram histogram(String name) {
    return get(new MetricID(name),
            new UnspecifiedMetadata(name, MetricType.HISTOGRAM));
}
 
Example #30
Source File: MetricProducer.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Produces
Histogram getHistogram(InjectionPoint ip) {
    Metadata metadata = getMetadata(ip, MetricType.HISTOGRAM);
    Tag[] tags = getTags(ip);
    return this.applicationRegistry.histogram(metadata, tags);
}