org.eclipse.microprofile.metrics.MetricID Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.MetricID. 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: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Counter,
 * check that the statistics from JsonExporter will not be scaled in any way.
 */
@Test
public void counter_json() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("counter1")
            .withType(MetricType.COUNTER)
            .build();
    Counter metric = registry.counter(metadata);
    metric.inc(10);
    metric.inc(20);
    metric.inc(30);

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

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject();
    assertEquals(60, json.getInt("counter1"));
}
 
Example #2
Source File: SimplyTimedClassBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Before
public void instantiateApplicationScopedBean() {
    // Let's trigger the instantiation of the application scoped bean
    // explicitly
    // as only a proxy gets injected otherwise
    bean.toString();
    /*
     * The MetricID relies on the MicroProfile Config API.
     * Running a managed arquillian container will result
     * with the MetricID being created in a client process
     * that does not contain the MPConfig impl.
     * 
     * This will cause client instantiated MetricIDs to 
     * throw an exception. (i.e the global MetricIDs)
     */
    constructorMID = new MetricID(CONSTRUCTOR_SIMPLE_TIMER_NAME);
    simpleTimerMIDs = MetricsUtil.createMetricIDs(SIMPLE_TIMER_NAMES);

    simpleTimerMIDsIncludingToString = new HashSet<>();
    simpleTimerMIDsIncludingToString.addAll(simpleTimerMIDs);
    simpleTimerMIDsIncludingToString.addAll(MetricsUtil.createMetricIDs(
        MetricsUtil.absoluteMetricNames(SimplyTimedClassBean.class, "simplyTimedClass", new String[] {"toString"})));
}
 
Example #3
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 JsonExporter will be presented in MINUTES.
 */
@Test
public void histogram_json() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("timer1")
            .withType(MetricType.TIMER)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Timer metric = registry.timer(metadata);
    metric.update(Duration.ofHours(1));
    metric.update(Duration.ofHours(2));
    metric.update(Duration.ofHours(3));

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

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject().getJsonObject("timer1");
    assertEquals(120.0, json.getJsonNumber("p50").doubleValue(), 0.001);
    assertEquals(120.0, json.getJsonNumber("mean").doubleValue(), 0.001);
    assertEquals(60.0, json.getJsonNumber("min").doubleValue(), 0.001);
    assertEquals(180.0, json.getJsonNumber("max").doubleValue(), 0.001);
}
 
Example #4
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * In OpenMetrics exporter and counters, if the metric name does not end with _total, then _total should be appended
 * automatically.
 * If it ends with _total, nothing extra will be appended.
 */
@Test
public void testAppendingOfTotal() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Tag tag = new Tag("a", "b");

    // in this case _total should be appended
    registry.counter("counter1", tag);
    String export = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("counter1", tag)).toString();
    assertThat(export, containsString("application_counter1_total{a=\"b\"}"));

    // in this case _total should NOT be appended
    registry.counter("counter2_total", tag);
    export = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("counter2_total", tag)).toString();
    assertThat(export, containsString("application_counter2_total{a=\"b\"}"));

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

    // Make sure that the metrics have been called
    assertThat("Counter count is incorrect", registry.getCounter(
            new MetricID(absoluteMetricName("counter"))).getCount(), is(equalTo(count)));
    assertThat("Meter count is incorrect", registry.getMeter(
            new MetricID(absoluteMetricName("meter"))).getCount(), is(equalTo(count)));
    assertThat("Timer count is incorrect", registry.getTimer(
            new MetricID(absoluteMetricName("timer"))).getCount(), is(equalTo(count)));
}
 
Example #6
Source File: TagsTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void lastTagValueTest() {
    
    Tag tagColour = new Tag("colour","red");
    Tag tagColourTwo = new Tag("colour","blue");
    
    String counterName = "org.eclipse.microprofile.metrics.tck.TagTest.counter";
    Counter counter = registry.counter(counterName, tagColour, tagColourTwo);
    
    //MetricID that only has colour=blue... the last tag value to be passed in
    MetricID counterMID = new MetricID(counterName, tagColourTwo);
    
    //check the metric is registered
    assertThat("Counter is not registered correctly", registry.getCounter(counterMID), notNullValue());
}
 
Example #7
Source File: AgroalMetricsTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsOfDs1() throws SQLException {
    Counter acquireCount = registry.getCounters().get(new MetricID("agroal.acquire.count",
            new Tag("datasource", "ds1")));
    Gauge<?> maxUsed = registry.getGauges().get(new MetricID("agroal.max.used.count",
            new Tag("datasource", "ds1")));
    Assertions.assertNotNull(acquireCount, "Agroal metrics should be registered eagerly");
    Assertions.assertNotNull(maxUsed, "Agroal metrics should be registered eagerly");

    try (Connection connection = ds1.getConnection()) {
        try (Statement statement = connection.createStatement()) {
            statement.execute("SELECT 1");
        }
    }

    Assertions.assertEquals(1L, acquireCount.getCount());
    Assertions.assertEquals(1L, maxUsed.getValue());
}
 
Example #8
Source File: TagsTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(1)
public void simpleTagTest() {
    Tag one = new Tag("hello", "world");
    Tag two = new Tag("goodbye", "friend");
    MetricID metricID = new MetricID("metricName", one, two);
    
    assertThat(metricID.getTags(), hasKey("hello"));
    assertThat(metricID.getTags(), hasValue("world"));
    
    assertThat(metricID.getTags(), hasKey("goodbye"));
    assertThat(metricID.getTags(), hasValue("friend"));
    
    //MP_METRICS_TAGS=tier=integration
    assertThat("Counter's Global Tag not set properly", metricID.getTags(), hasKey("tier"));
    assertThat("Counter's Global Tag not set properly", metricID.getTags(), hasValue("integration"));
}
 
Example #9
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 #10
Source File: SimplyTimedInterceptor.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private <E extends Member & AnnotatedElement> Object timedCallable(InvocationContext invocationContext, E element)
        throws Exception {
    Set<MetricID> ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
            .getSimpleTimers(new CDIMemberInfoAdapter<>().convert(element));
    if (ids == null || ids.isEmpty()) {
        throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
    }
    List<SimpleTimer.Context> contexts = ids.stream()
            .map(metricID -> {
                SimpleTimer metric = registry.getSimpleTimers().get(metricID);
                if (metric == null) {
                    throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.SIMPLE_TIMER, metricID);
                }
                return metric;
            })
            .map(SimpleTimer::time)
            .collect(Collectors.toList());
    try {
        return invocationContext.proceed();
    } finally {
        for (SimpleTimer.Context timeContext : contexts) {
            timeContext.stop();
        }
    }
}
 
Example #11
Source File: TimerTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(3)
public void testTimerRegistry() throws Exception {
    String timerLongName = "test.longData.timer";
    String timerTimeName = "testTime";

    MetricID timerLongNameMetricID = new MetricID(timerLongName);
    MetricID timerTimeNameMetricID = new MetricID(timerTimeName);

    Timer timerLong = registry.getTimer(timerLongNameMetricID);
    Timer timerTime = registry.getTimer(timerTimeNameMetricID);

    assertNotNull(timerLong);
    assertNotNull(timerTime);

    TestUtils.assertEqualsWithTolerance(480, timerLong.getSnapshot().getValue(0.5));
}
 
Example #12
Source File: ApplicationScopedTimedMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Before
public void instantiateApplicationScopedBeanAndTests() {
    // Let's trigger the instantiation of the application scoped bean explicitly
    // as only a proxy gets injected otherwise
    bean.toString();
    /*
     * The MetricID relies on the MicroProfile Config API.
     * Running a managed arquillian container will result
     * with the MetricID being created in a client process
     * that does not contain the MPConfig impl.
     * 
     * This will cause client instantiated MetricIDs to 
     * throw an exception. (i.e the global MetricIDs)
     */
    timerMID = new MetricID(TIMER_NAME);
}
 
Example #13
Source File: JaxRsMetricsFilter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private MetricID getMetricID(Class<?> resourceClass, Method resourceMethod) {
    Tag classTag = new Tag("class", resourceClass.getName());
    String methodName = resourceMethod.getName();
    String encodedParameterNames = Arrays.stream(resourceMethod.getParameterTypes())
            .map(clazz -> {
                if (clazz.isArray()) {
                    return clazz.getComponentType().getName() + "[]";
                } else {
                    return clazz.getName();
                }
            })
            .collect(Collectors.joining("_"));
    String methodTagValue = encodedParameterNames.isEmpty() ? methodName : methodName + "_" + encodedParameterNames;
    Tag methodTag = new Tag("method", methodTagValue);
    return new MetricID("REST.request", classTag, methodTag);
}
 
Example #14
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 #15
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 #16
Source File: QuarkusJaxRsMetricsFilter.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private MetricID getMetricID(Class<?> resourceClass, Method resourceMethod) {
    Tag classTag = new Tag("class", resourceClass.getName());
    String methodName = resourceMethod.getName();
    String encodedParameterNames = Arrays.stream(resourceMethod.getParameterTypes())
            .map(clazz -> {
                if (clazz.isArray()) {
                    return clazz.getComponentType().getName() + "[]";
                } else {
                    return clazz.getName();
                }
            })
            .collect(Collectors.joining("_"));
    String methodTagValue = encodedParameterNames.isEmpty() ? methodName : methodName + "_" + encodedParameterNames;
    Tag methodTag = new Tag("method", methodTagValue);
    return new MetricID("REST.request", classTag, methodTag);
}
 
Example #17
Source File: MemberToMetricMappings.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
public void addMetric(MemberInfo member, MetricID metricID, MetricType metricType) {
    switch (metricType) {
        case COUNTER:
            counters.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case CONCURRENT_GAUGE:
            concurrentGauges.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case METERED:
            meters.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case TIMER:
            timers.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case SIMPLE_TIMER:
            simpleTimers.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        default:
            throw SmallRyeMetricsMessages.msg.unknownMetricType();
    }
    SmallRyeMetricsLogging.log.matchingMemberToMetric(member, metricID, metricType);
}
 
Example #18
Source File: MetricsTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testQuery() {
    SimpleTimer metric = metricRegistry.getSimpleTimers().get(new MetricID("mp_graphql_Query_ping"));
    assertNotNull(metric, "Metrics should be registered eagerly");

    String pingRequest = getPayload("{\n" +
            "  ping {\n" +
            "    message\n" +
            "  }\n" +
            "}");

    RestAssured.given().when()
            .accept("application/json")
            .contentType("application/json")
            .body(pingRequest)
            .post("/graphql")
            .then()
            .assertThat()
            .statusCode(200)
            .and()
            .body(CoreMatchers.containsString("{\"data\":{\"ping\":{\"message\":\"pong\"}}}"));

    assertEquals(1L, metric.getCount(), "Metric should be updated after querying");
}
 
Example #19
Source File: StereotypeCountedClassBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithMetadata() {
    String constructorMetricName = "org.eclipse.microprofile.metrics.tck.cdi.stereotype.bloop.StereotypeCountedClassBeanWithSpecifiedMetadata";
    MetricID constructorMetricId = new MetricID(constructorMetricName);
    assertNotNull(metricRegistry.getCounter(constructorMetricId));
    Metadata constructorMetadata = metricRegistry.getMetadata(constructorMetricName);
    assertEquals("description", constructorMetadata.description().orElse(null));
    assertEquals("displayName", constructorMetadata.getDisplayName());

    String methodMetricName = "org.eclipse.microprofile.metrics.tck.cdi.stereotype.bloop.foo";
    MetricID methodMetricId = new MetricID(methodMetricName);
    assertNotNull(metricRegistry.getCounter(methodMetricId));
    Metadata methodMetadata = metricRegistry.getMetadata(methodMetricName);
    assertEquals("description", methodMetadata.description().orElse(null));
    assertEquals("displayName", methodMetadata.getDisplayName());

    beanWithSpecifiedMetadata.foo();
    assertEquals(1, metricRegistry.getCounter(methodMetricId).getCount());
}
 
Example #20
Source File: ConcurrentGaugedConstructorBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Before
public void instantiateTest() {
    /*
     * The MetricID relies on the MicroProfile Config API.
     * Running a managed arquillian container will result
     * with the MetricID being created in a client process
     * that does not contain the MPConfig impl.
     * 
     * This will cause client instantiated MetricIDs to 
     * throw an exception. (i.e the global MetricIDs)
     */
    counterMID = new MetricID(COUNTER_NAME);
}
 
Example #21
Source File: MetricsInheritanceResource.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/registration")
@GET
@Produces("application/json")
public List<String> getAllMetricNames() {
    return metricRegistry
            .getCounters((metricID, metric) -> metricID.getName().contains("Inheritance"))
            .keySet()
            .stream()
            .map(MetricID::getName)
            .collect(Collectors.toList());
}
 
Example #22
Source File: StereotypeCountedClassTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    MetricID id_constructor = new MetricID(CountedClass.class.getName() + ".CountedClass");
    assertTrue(metricRegistry.getCounters().containsKey(id_constructor));
    MetricID id_method = new MetricID(CountedClass.class.getName() + ".foo");
    assertTrue(metricRegistry.getCounters().containsKey(id_method));
    bean.foo();
    assertEquals(1, metricRegistry.getCounters().get(id_method).getCount());
}
 
Example #23
Source File: RegistrationCornerCasesTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void lambdaExpressionCastToMultipleInterfaces() {
    registry.register("test", (DummyInterface & Gauge<Long>) () -> 18L);

    Assert.assertEquals(MetricType.GAUGE, registry.getMetadata("test").getTypeRaw());
    Assert.assertEquals(18L, registry.getGauge(new MetricID("test")).getValue());
}
 
Example #24
Source File: RegistrationCornerCasesTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void anonymousClassThatImplementsMetricViaSuperClass() {
    registry.register("test", new Bax() {
        @Override
        public long getCount() {
            return 145;
        }
    });

    Assert.assertEquals(MetricType.COUNTER, registry.getMetadata("test").getTypeRaw());
    Assert.assertEquals(145, registry.getCounter(new MetricID("test")).getCount());
}
 
Example #25
Source File: Initialization_ProducerField_Test.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    MetricID metricID = new MetricID("counter1");
    // check eager initialization here
    assertTrue(registry.getCounters().containsKey(metricID));
    assertEquals(0, registry.getCounters().get(metricID).getCount());
    bean.addDataToCounter();
    Counter counter = registry.getCounters().get(metricID);
    assertEquals(1, counter.getCount());
}
 
Example #26
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public boolean remove(String metricName) {
    SmallRyeMetricsLogging.log.removeMetricsByName(metricName);
    // iterate over all metricID's in the map and remove the ones with this name
    for (MetricID metricID : metricMap.keySet()) {
        if (metricID.getName().equals(metricName)) {
            metricMap.remove(metricID);
        }
    }
    // dispose of the metadata as well
    return metadataMap.remove(metricName) != null;
}
 
Example #27
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private JsonObject exportOneRegistry(MetricRegistry registry) {
    Map<MetricID, Metric> metricMap = registry.getMetrics();
    Map<String, Metadata> metadataMap = registry.getMetadata();

    JsonObjectBuilder root = JsonProviderHolder.get().createObjectBuilder();
    exportMetricsForMap(metricMap, metadataMap)
            .forEach(root::add);
    return root.build();
}
 
Example #28
Source File: SimplyTimedTagMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Before
public void instantiateTest() {
    /*
     * The MetricID relies on the MicroProfile Config API.
     * Running a managed arquillian container will result
     * with the MetricID being created in a client process
     * that does not contain the MPConfig impl.
     * 
     * This will cause client instantiated MetricIDs to 
     * throw an exception. (i.e the global MetricIDs)
     */
    simpleTimerOneMID = new MetricID(SIMPLE_TIMER_NAME, NUMBER_ONE_TAG);
    simpleTimerTwoMID = new MetricID(SIMPLE_TIMER_NAME, NUMBER_TWO_TAG);

}
 
Example #29
Source File: MetricsInDependentScopedBeanTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void counter() {
    DependentScopedBeanWithMetrics instance1 = beanInstance.get();
    DependentScopedBeanWithMetrics instance2 = beanInstance.get();

    instance1.countedMethod();
    instance2.countedMethod();

    assertEquals(2, registry.getCounters().get(new MetricID("counter")).getCount());
}
 
Example #30
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * OpenMetrics exporter should only emit a HELP line if a description exists and is not empty
 */
@Test
public void testEmptyDescription() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = Metadata.builder()
            .withName("counter_with_empty_description")
            .withDescription("").build();
    registry.counter(metadata);
    String export = exporter
            .exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("counter_with_empty_description")).toString();
    assertThat(export, not(containsString("HELP")));
}