Java Code Examples for org.eclipse.microprofile.metrics.MetricID

The following examples show how to use org.eclipse.microprofile.metrics.MetricID. These examples are extracted from open source projects. 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 Project: quarkus   Source File: MetricsTest.java    License: 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 2
Source Project: microprofile-metrics   Source File: TimerTest.java    License: 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 3
Source Project: smallrye-metrics   Source File: SimplyTimedInterceptor.java    License: 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 4
Source Project: smallrye-metrics   Source File: MeteredInterceptor.java    License: 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 5
@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 Project: microprofile-metrics   Source File: TagsTest.java    License: 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 Project: microprofile-metrics   Source File: TagsTest.java    License: 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 8
Source Project: microprofile-metrics   Source File: MetricRegistryTest.java    License: 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 Project: smallrye-metrics   Source File: MemberToMetricMappings.java    License: 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 10
@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 11
/**
 * 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 12
@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 13
/**
 * 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 14
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: 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 15
Source Project: quarkus   Source File: AgroalMetricsTestCase.java    License: 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 16
@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 17
Source Project: smallrye-metrics   Source File: JaxRsMetricsFilter.java    License: 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 18
Source Project: microprofile-metrics   Source File: TagsTest.java    License: 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 19
Source Project: quarkus   Source File: QuarkusJaxRsMetricsFilter.java    License: 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 20
Source Project: smallrye-graphql   Source File: MetricTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(99)
public void verifyMetricsAreRegisteredEagerly() {
    SimpleTimer metricForHelloQuery = metricRegistry.getSimpleTimers().get(new MetricID("mp_graphql_Query_get"));
    Assert.assertNotNull("Metric should be registered eagerly", metricForHelloQuery);

    SimpleTimer metricForMutation = metricRegistry.getSimpleTimers().get(new MetricID("mp_graphql_Mutation_mutate"));
    Assert.assertNotNull("Metric should be registered eagerly", metricForMutation);

    SimpleTimer metricForSource = metricRegistry.getSimpleTimers().get(new MetricID("mp_graphql_Foo_description"));
    Assert.assertNotNull("Metric should be registered eagerly", metricForSource);
}
 
Example 21
@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)
     */
    meterMID = new MetricID(METER_NAME);
}
 
Example 22
@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)
     */
    simpleTimerMID = new MetricID(SIMPLE_TIMER_NAME);
}
 
Example 23
Source Project: microprofile-metrics   Source File: CountedClassBeanTest.java    License: 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)
     */
    constructorMID = new MetricID(CONSTRUCTOR_COUNTER_NAME);
    counterMIDs = MetricsUtil.createMetricIDs(COUNTER_NAMES);
}
 
Example 24
@Override
public void connectionCheckedIn(ConnectionCheckedInEvent event) {
    MetricID metricID = createMetricID(CHECKED_OUT_COUNT_NAME, event.getConnectionId().getServerId());

    Metric metric = getMetricRegistry().getMetrics().get(metricID);

    if (metric != null) {
        ((ConnectionPoolGauge) metric).decrement();
    }
}
 
Example 25
private void gaugeRegister(String name, Supplier<Long> supplier) {
    MetricID metricID = new MetricID(name);
    Gauge<?> gauge = registry.getGauges().get(metricID);
    if (gauge == null) {
        synchronized (operation) {
            gauge = registry.getGauges().get(metricID);
            if (gauge == null) {
                registry.register(name, (Gauge<Long>) supplier::get);
            }
        }
    }
}
 
Example 26
private Counter counterOf(String name) {
    MetricID metricID = new MetricID(name);
    Counter counter = registry.getCounters().get(metricID);
    if (counter == null) {
        synchronized (operation) {
            counter = registry.getCounters().get(metricID);
            if (counter == null) {
                counter = registry.counter(metadataOf(name, MetricType.COUNTER));
            }
        }
    }
    return counter;
}
 
Example 27
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 28
private Counter getMessageCounterForChannel(String channel) {
    Map<MetricID, Counter> counters = metricRegistry.getCounters((id, m) -> id.getName().equals("mp.messaging.message.count")
            && id.getTags().getOrDefault("channel", "").equals(channel));
    
    assertThat(counters.entrySet(), hasSize(1));
    
    return counters.values().iterator().next();
}
 
Example 29
/**
 * With a gauge in an application-scoped bean, the metric will be registered once the bean is instantiated.
 */
@Test
public void testApplicationScoped() {
    applicationScopedBean.gauge(); // access the application-scoped bean so that an instance gets created
    assertTrue(registry.getGauges().containsKey(new MetricID("gaugeApp")));
    Assert.assertEquals(2L, registry.getGauges().get(new MetricID("gaugeApp")).getValue());
    Assert.assertEquals(3L, registry.getGauges().get(new MetricID("gaugeApp")).getValue());
}
 
Example 30
/**
 * One set of threads is registering new metrics and removing them after a short while,
 * at the same time, another set of threads is retrieving a list of metrics conforming to a filter.
 * None of the threads should be getting any exceptions.
 */
@Test
public void tryRegisteringRemovingAndReadingAtTheSameTime() throws InterruptedException {
    for (int i = 0; i < 20; i++) {
        cleanup();
        final ExecutorService executor = Executors.newFixedThreadPool(10);
        final CompletableFuture[] futures = IntStream.range(0, 200)
                .parallel()
                .mapToObj(j -> CompletableFuture.runAsync(
                        () -> {
                            try {
                                if (j % 2 == 0) {
                                    MetricID metricID = new MetricID("mycounter", new Tag("number", String.valueOf(j)));
                                    registry.counter("mycounter", new Tag("number", String.valueOf(j)));
                                    registry.remove(metricID);
                                } else {
                                    registry.getCounters(MetricFilter.ALL);
                                }
                            } catch (Throwable t) {
                                t.printStackTrace();
                                throw t;
                            }
                        }, executor))
                .toArray(CompletableFuture[]::new);
        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.SECONDS);

        assertEquals("All threads should finish without exceptions",
                0, Arrays.stream(futures).filter(CompletableFuture::isCompletedExceptionally).count());
    }
}