org.eclipse.microprofile.metrics.Meter Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.Meter. 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: MeteredMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(3)
public void removeMeterFromRegistry() {
    Meter meter = registry.getMeter(meterMID);
    assertThat("Meter is not registered correctly", meter, notNullValue());

    // Remove the meter from metrics registry
    registry.remove(meterMID);

    try {
        // Call the metered method and assert an exception is thrown
        bean.meteredMethod();
    }
    catch (RuntimeException cause) {
        assertThat(cause, is(instanceOf(IllegalStateException.class)));
        // Make sure that the meter hasn't been marked
        assertThat("Meter count is incorrect", meter.getCount(), is(equalTo(METER_COUNT.get())));
        return;
    }

    fail("No exception has been re-thrown!");
}
 
Example #2
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentMeterImplementations() {

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

    // the export should behave identical for any class derived from Meter
    Meter[] meters = { new MeterImpl(), new SomeMeter() };
    int idx = 0;
    for (Meter m : meters) {
        String name = "meter_" + idx++;
        applicationRegistry.register(name, m);
        String out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name)).toString();
        String expectedLine = "application_" + name + "_total 0.0";
        assertThat(out, containsString(expectedLine));
    }
}
 
Example #3
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Meter,
 * check that the statistics from JsonExporter will be presented as per_second.
 */
@Test
public void meter_json() throws InterruptedException {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("meter1")
            .withType(MetricType.METERED)
            .build();
    Meter metric = registry.meter(metadata);
    metric.mark(10);
    TimeUnit.SECONDS.sleep(1);

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

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject().getJsonObject("meter1");
    assertEquals(10, json.getInt("count"));
    double meanRate = json.getJsonNumber("meanRate").doubleValue();
    Assert.assertTrue("meanRate should be between 1 and 10 but is " + meanRate,
            meanRate > 1 && meanRate < 10);
}
 
Example #4
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Meter,
 * check that the statistics from OpenMetrics will be presented as per_second.
 */
@Test
public void meter_openMetrics() throws InterruptedException {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("meter1")
            .withType(MetricType.METERED)
            .build();
    Meter metric = registry.meter(metadata);
    metric.mark(10);
    TimeUnit.SECONDS.sleep(1);

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

    Assert.assertThat(exported, containsString("application_meter1_total 10.0"));
    double ratePerSecond = Double.parseDouble(Arrays.stream(exported.split("\\n"))
            .filter(line -> line.contains("application_meter1_rate_per_second"))
            .filter(line -> !line.contains("TYPE") && !line.contains("HELP"))
            .findFirst()
            .get()
            .split(" ")[1]);
    Assert.assertTrue("Rate per second should be between 1 and 10 but is " + ratePerSecond,
            ratePerSecond > 1 && ratePerSecond < 10);
}
 
Example #5
Source File: MeteredInterceptor.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private <E extends Member & AnnotatedElement> Object meteredCallable(InvocationContext context, E element)
        throws Exception {
    Set<MetricID> ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
            .getMeters(new CDIMemberInfoAdapter<>().convert(element));
    if (ids == null || ids.isEmpty()) {
        throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
    }
    ids.stream()
            .map(metricID -> {
                Meter metric = registry.getMeters().get(metricID);
                if (metric == null) {
                    throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.METERED, metricID);
                }
                return metric;
            })
            .forEach(Meter::mark);
    return context.proceed();
}
 
Example #6
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentMeterImplementations() {

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

    // the export should behave identical for any class derived from Meter
    Meter[] meters = { new MeterImpl(), new SomeMeter() };
    int idx = 0;
    for (Meter m : meters) {
        String name = "meter_" + idx++;
        applicationRegistry.register(name, m);
        StringBuilder out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name));
        assertNotNull(out);
        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 #7
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 #8
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 #9
Source File: MeteredClassBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void callMeteredMethodsOnce() {        
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(meterMIDs)));
    
    // Call the metered methods and assert they've been marked
    bean.meteredMethodOne();
    bean.meteredMethodTwo();
    // Let's call the non-public methods as well
    bean.meteredMethodProtected();
    bean.meteredMethodPackagedPrivate();

    // Make sure that the method meters have been marked
    assertThat("Method meter counts are incorrect", registry.getMeters(METHOD_METERS).values(),
            everyItem(Matchers.<Meter> hasProperty("count", equalTo(METHOD_COUNT.incrementAndGet()))));

    assertThat("Constructor's metric should be incremented at least once",
        registry.getMeter(constructorMID).getCount(), is(greaterThanOrEqualTo(1L)));
}
 
Example #10
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 #11
Source File: TagsTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(4)
public void meterTagsTest() {
    
    Tag tagEarth = new Tag("planet", "earth");
    Tag tagRed = new Tag("colour", "red");
    Tag tagBlue = new Tag("colour", "blue");
    
    String meterName = "org.eclipse.microprofile.metrics.tck.TagTest.meterColour";
    
    Meter meterColour = registry.meter(meterName);
    Meter meterRed = registry.meter(meterName,tagEarth,tagRed);
    Meter meterBlue = registry.meter(meterName,tagEarth,tagBlue);
    
    MetricID meterColourMID = new MetricID(meterName);
    MetricID meterRedMID = new MetricID(meterName, tagEarth,tagRed);
    MetricID meterBlueMID = new MetricID(meterName, tagEarth,tagBlue);
    
    //check multi-dimensional metrics are registered
    assertThat("Meter is not registered correctly", registry.getMeter(meterColourMID), notNullValue());
    assertThat("Meter is not registered correctly", registry.getMeter(meterRedMID), notNullValue());
    assertThat("Meter is not registered correctly", registry.getMeter(meterBlueMID), notNullValue());
}
 
Example #12
Source File: MetricProducerMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void callCachedMethodMultipleTimes() {
    assertThat("Metrics are not registered correctly", registry.getMetricIDs(),
        contains(cacheHitsMID, callsMID, hitsMID));
    Timer calls = registry.getTimer(callsMID);
    Meter hits = registry.getMeter(hitsMID);
    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(cacheHitsMID);

    long count = 10 + Math.round(Math.random() * 10);
    for (int i = 0; i < count; i++) {
        bean.cachedMethod((Math.random() < 0.5));
    }

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo((double) hits.getCount() / (double) calls.getCount())));
}
 
Example #13
Source File: MeterTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testRates() throws Exception {

    int count = 100;
    int markSeconds = 30;
    int delaySeconds = 15;
    
    Meter meter = registry.meter("testMeterRatesLong");
    
    for (int i = 0; i < markSeconds; i++) {
        meter.mark(count);
        Thread.sleep(1000);
    }

    // All rates should be around the value of count
    TestUtils.assertEqualsWithTolerance(count, meter.getMeanRate());
    TestUtils.assertEqualsWithTolerance(count, meter.getOneMinuteRate());
    TestUtils.assertEqualsWithTolerance(count, meter.getFiveMinuteRate());
    TestUtils.assertEqualsWithTolerance(count, meter.getFifteenMinuteRate());
            
    Thread.sleep(delaySeconds * 1000);
    
    // Approximately calculate what the expected mean should be
    // and let the tolerance account for the delta
    double expectedMean = count * ((double) markSeconds/(markSeconds + delaySeconds));
    TestUtils.assertEqualsWithTolerance(expectedMean, meter.getMeanRate());
    
    // After a delay, we expect some decay of values
    Assert.assertThat(meter.getOneMinuteRate(), lessThan((double)count));
    Assert.assertThat(meter.getFiveMinuteRate(), lessThan((double)count));
    Assert.assertThat(meter.getFifteenMinuteRate(), lessThan((double)count));

}
 
Example #14
Source File: MeteredConstructorBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void meteredConstructorCalled() {
    long count = 1L + Math.round(Math.random() * 10);
    for (int i = 0; i < count; i++) {
        instance.get();
    }

    Meter meter = registry.getMeter(meterMID);
    assertThat("Meter is not registered correctly", meter, notNullValue());

    // Make sure that the meter has been called
    assertThat("Meter count is incorrect", meter.getCount(), is(equalTo(count)));
}
 
Example #15
Source File: MeteredMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(2)
public void callMeteredMethodOnce() {
    Meter meter = registry.getMeter(meterMID);
    assertThat("Meter is not registered correctly", meter, notNullValue());

    // Call the metered method and assert it's been marked
    bean.meteredMethod();

    // Make sure that the meter has been marked
    assertThat("Timer count is incorrect", meter.getCount(), is(equalTo(METER_COUNT.incrementAndGet())));
}
 
Example #16
Source File: MeteredMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void meteredMethodNotCalledYet() {
    Meter meter = registry.getMeter(meterMID);
    assertThat("Meter is not registered correctly", meter, notNullValue());

    // Make sure that the meter hasn't been marked yet
    assertThat("Meter count is incorrect", meter.getCount(), is(equalTo(METER_COUNT.get())));
}
 
Example #17
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testMeters() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Meter meterWithoutTags = registry.meter("mymeter");
    Meter meterRed = registry.meter("mymeter", new Tag("color", "red"));
    Meter meterBlue = registry.meter("mymeter", new Tag("color", "blue"), new Tag("foo", "bar"));

    meterWithoutTags.mark(1);
    meterRed.mark(2);
    meterBlue.mark(3);

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "mymeter").toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    JsonObject myMeterObject = json.getJsonObject("mymeter");
    assertEquals(1, myMeterObject.getInt("count"));
    assertEquals(2, myMeterObject.getInt("count;color=red"));
    assertEquals(3, myMeterObject.getInt("count;color=blue;foo=bar"));

    assertNotNull(myMeterObject.getJsonNumber("meanRate"));
    assertNotNull(myMeterObject.getJsonNumber("meanRate;color=red"));
    assertNotNull(myMeterObject.getJsonNumber("meanRate;color=blue;foo=bar"));

    assertNotNull(myMeterObject.getJsonNumber("oneMinRate"));
    assertNotNull(myMeterObject.getJsonNumber("oneMinRate;color=red"));
    assertNotNull(myMeterObject.getJsonNumber("oneMinRate;color=blue;foo=bar"));

    assertNotNull(myMeterObject.getJsonNumber("fiveMinRate"));
    assertNotNull(myMeterObject.getJsonNumber("fiveMinRate;color=red"));
    assertNotNull(myMeterObject.getJsonNumber("fiveMinRate;color=blue;foo=bar"));

    assertNotNull(myMeterObject.getJsonNumber("fifteenMinRate"));
    assertNotNull(myMeterObject.getJsonNumber("fifteenMinRate;color=red"));
    assertNotNull(myMeterObject.getJsonNumber("fifteenMinRate;color=blue;foo=bar"));
}
 
Example #18
Source File: MeteredClassBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void meteredMethodsNotCalledYet() {
    assertThat("Meters are not registered correctly", registry.getMeters().keySet(), is(equalTo(meterMIDs)));

    // Make sure that the method meters haven't been marked yet
    assertThat("Method meter counts are incorrect", registry.getMeters(METHOD_METERS).values(), 
            everyItem(Matchers.<Meter>hasProperty("count", equalTo(METHOD_COUNT.get()))));

}
 
Example #19
Source File: MetricProducerMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void cachedMethodNotCalledYet() {
    assertThat("Metrics are not registered correctly", registry.getMetricIDs(),
        contains(cacheHitsMID, callsMID, hitsMID));
    Timer calls = registry.getTimer(callsMID);
    Meter hits = registry.getMeter(hitsMID);
    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(cacheHitsMID);

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) hits.getCount() / (double) calls.getCount()))));
}
 
Example #20
Source File: MetricProducerMethodBean.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Produces
@Metric(name = "cache-hits")
Gauge<Double> cacheHitRatioGauge(final @Metric(name = "hits") Meter hits, final @Metric(name = "calls") Timer calls) {
    return new Gauge<Double>() {

        @Override
        public Double getValue() {
            return (double) hits.getCount() / (double) calls.getCount();
        }
    };

}
 
Example #21
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public Meter meter(String name, Tag... tags) {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #22
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Test
public void exportMeters() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = Metadata
            .builder()
            .withType(MetricType.METERED)
            .withName("mymeter")
            .withDescription("awesome")
            .build();
    Tag blueTag = new Tag("color", "blue");
    Meter blueMeter = registry.meter(metadata, blueTag);
    Tag greenTag = new Tag("color", "green");
    Meter greenMeter = registry.meter(metadata, greenTag);

    blueMeter.mark(20);
    greenMeter.mark(10);

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "mymeter").toString();
    System.out.println(result);

    assertHasTypeLineExactlyOnce(result, "application_mymeter_total", "counter");
    assertHasHelpLineExactlyOnce(result, "application_mymeter_total", "awesome");
    assertHasValueLineExactlyOnce(result, "application_mymeter_total", "20.0", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mymeter_total", "10.0", greenTag);

    assertHasTypeLineExactlyOnce(result, "application_mymeter_rate_per_second", "gauge");
    assertHasValueLineExactlyOnce(result, "application_mymeter_rate_per_second", "*", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mymeter_rate_per_second", "*", greenTag);

    assertHasTypeLineExactlyOnce(result, "application_mymeter_one_min_rate_per_second", "gauge");
    assertHasValueLineExactlyOnce(result, "application_mymeter_one_min_rate_per_second", "*", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mymeter_one_min_rate_per_second", "*", greenTag);

    assertHasTypeLineExactlyOnce(result, "application_mymeter_five_min_rate_per_second", "gauge");
    assertHasValueLineExactlyOnce(result, "application_mymeter_five_min_rate_per_second", "*", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mymeter_five_min_rate_per_second", "*", greenTag);

    assertHasTypeLineExactlyOnce(result, "application_mymeter_fifteen_min_rate_per_second", "gauge");
    assertHasValueLineExactlyOnce(result, "application_mymeter_fifteen_min_rate_per_second", "*", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mymeter_fifteen_min_rate_per_second", "*", greenTag);
}
 
Example #23
Source File: MetricProducer.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Produces
Meter getMeter(InjectionPoint ip) {
    Metadata metadata = getMetadata(ip, MetricType.METERED);
    Tag[] tags = getTags(ip);
    return this.applicationRegistry.meter(metadata, tags);
}
 
Example #24
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Meter getMeter(MetricID metricID) {
    return getMetric(metricID, Meter.class);
}
 
Example #25
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public java.util.SortedMap<MetricID, Meter> getMeters(MetricFilter metricFilter) {
    return getMetrics(MetricType.METERED, metricFilter);
}
 
Example #26
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public java.util.SortedMap<MetricID, Meter> getMeters() {
    return getMeters(MetricFilter.ALL);
}
 
Example #27
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Meter meter(Metadata metadata, Tag... tags) {
    return get(new MetricID(metadata.getName(), tags), sanitizeMetadata(metadata, MetricType.METERED));
}
 
Example #28
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Meter meter(String name, Tag... tags) {
    return get(new MetricID(name, tags),
            new UnspecifiedMetadata(name, MetricType.METERED));
}
 
Example #29
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Meter meter(MetricID metricID) {
    return get(metricID, new UnspecifiedMetadata(metricID.getName(), MetricType.METERED));
}
 
Example #30
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public Meter meter(Metadata metadata) {
    return get(new MetricID(metadata.getName()), sanitizeMetadata(metadata, MetricType.METERED));
}