org.eclipse.microprofile.metrics.Tag Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.Tag. 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: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testNameOverride() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = new ExtendedMetadata("voltage1",
            "Voltage",
            "Measures your electric potential",
            MetricType.GAUGE,
            "volts",
            null,
            false,
            Optional.of(true),
            false,
            "baz");
    Tag tag = new Tag("a", "b");
    registry.register(metadata, (Gauge<Long>) () -> 3L, tag);

    String result = exporter.exportOneScope(MetricRegistry.Type.APPLICATION).toString();
    System.out.println(result);
    assertHasHelpLineExactlyOnce(result, "application_baz", "Measures your electric potential");
    assertHasTypeLineExactlyOnce(result, "application_baz", "gauge");
    assertHasValueLineExactlyOnce(result, "application_baz", "3.0", tag);
}
 
Example #2
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 #3
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testCounters() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Counter counterWithoutTags = registry.counter("mycounter");
    Counter counterRed = registry.counter("mycounter", new Tag("color", "red"));
    Counter counterBlue = registry.counter("mycounter", new Tag("color", "blue"), new Tag("foo", "bar"));

    counterWithoutTags.inc(1);
    counterRed.inc(2);
    counterBlue.inc(3);

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

    assertEquals(1, json.getInt("mycounter"));
    assertEquals(2, json.getInt("mycounter;color=red"));
    assertEquals(3, json.getInt("mycounter;color=blue;foo=bar"));
}
 
Example #4
Source File: JmxRegistrar.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private ExtendedMetadataAndTags metadataOf(Map.Entry<String, List<MetricProperty>> metadataEntry) {
    String name = metadataEntry.getKey();
    Map<String, String> entryProperties = new HashMap<>();
    metadataEntry.getValue()
            .forEach(
                    prop -> entryProperties.put(prop.propertyKey, prop.propertyValue));
    List<Tag> tags = new ArrayList<>();
    if (entryProperties.containsKey("tags")) {
        final String labelDefs[] = entryProperties.get("tags").split(";");
        for (final String labelDef : labelDefs) {
            final String label[] = labelDef.split("=", 2);
            final Tag tag = new Tag(label[0], label[1]);
            tags.add(tag);
        }
    }

    ExtendedMetadata meta = new ExtendedMetadata(name, entryProperties.get("displayName"),
            entryProperties.get("description"),
            metricTypeOf(entryProperties.get("type")),
            entryProperties.get("unit"),
            entryProperties.get("mbean"),
            "true".equalsIgnoreCase(entryProperties.get("multi")));

    return new ExtendedMetadataAndTags(meta, tags);
}
 
Example #5
Source File: JsonMetadataExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void exportByMetricNameWithMultipleMetrics() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1", new Tag("key1", "value1"));
    applicationRegistry.counter("counter1", new Tag("key1", "value2"));
    applicationRegistry.counter("counter1", new Tag("key1", "value3"));

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

    JsonArray outerTagsArray = json.getJsonObject("counter1").getJsonArray("tags");
    assertEquals(3, outerTagsArray.size());

    JsonArray innerArray1 = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray1.size());
    assertEquals("key1=value1", innerArray1.getString(0));

    JsonArray innerArray2 = outerTagsArray.getJsonArray(1);
    assertEquals(1, innerArray2.size());
    assertEquals("key1=value2", innerArray2.getString(0));

    JsonArray innerArray3 = outerTagsArray.getJsonArray(2);
    assertEquals(1, innerArray3.size());
    assertEquals("key1=value3", innerArray3.getString(0));
}
 
Example #6
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 #7
Source File: AgroalMetricsTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsOfDefaultDS() throws SQLException {
    Counter acquireCount = registry.getCounters().get(new MetricID("agroal.acquire.count",
            new Tag("datasource", "default")));
    Gauge<?> maxUsed = registry.getGauges().get(new MetricID("agroal.max.used.count",
            new Tag("datasource", "default")));
    Assertions.assertNotNull(acquireCount, "Agroal metrics should be registered eagerly");
    Assertions.assertNotNull(maxUsed, "Agroal metrics should be registered eagerly");

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

    Assertions.assertEquals(1L, acquireCount.getCount());
    Assertions.assertEquals(1L, maxUsed.getValue());
}
 
Example #8
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testSkippingOfScope() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = new ExtendedMetadata("foo",
            "foo",
            "FooDescription",
            MetricType.COUNTER,
            "volts",
            null,
            false,
            Optional.of(true),
            true,
            null);
    Tag tag = new Tag("a", "b");
    registry.counter(metadata, tag);

    String result = exporter.exportOneScope(MetricRegistry.Type.APPLICATION).toString();
    System.out.println(result);
    assertHasHelpLineExactlyOnce(result, "foo_total", "FooDescription");
    assertHasTypeLineExactlyOnce(result, "foo_total", "counter");
    assertHasValueLineExactlyOnce(result, "foo_total_volts", "0.0", tag);
}
 
Example #9
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoubleQuotesInTagValue() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    registry.counter("counter1",
            new Tag("tag1", "i_have\"quotes\""));

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

    assertEquals("Double quotes in tag values should be escaped", "counter1;tag1=i_have\"quotes\"",
            json.keySet().stream().findFirst().get());
}
 
Example #10
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * Test prependsScopeToOpenMetricsName in the ExtendedMetadata
 */
@Test
public void testMicroProfileScopeInTagsWithExtendedMetadata() {

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

    Metadata metadata = new ExtendedMetadata("mycounter", "mycounter", "awesome", MetricType.COUNTER,
            "none", null, false, Optional.of(false));
    Tag colourTag = new Tag("color", "blue");
    Counter counterWithTag = registry.counter(metadata, colourTag);
    Counter counterWithoutTag = registry.counter(metadata);

    counterWithTag.inc(10);
    counterWithoutTag.inc(20);

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

    Tag microProfileScopeTag = new Tag("microprofile_scope", MetricRegistry.Type.APPLICATION.getName().toLowerCase());

    assertHasTypeLineExactlyOnce(result, "mycounter_total", "counter");
    assertHasHelpLineExactlyOnce(result, "mycounter_total", "awesome");

    assertHasValueLineExactlyOnce(result, "mycounter_total", "10.0", colourTag, microProfileScopeTag);
    assertHasValueLineExactlyOnce(result, "mycounter_total", "20.0", microProfileScopeTag);
}
 
Example #11
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void exportConcurrentGauges() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = Metadata
            .builder()
            .withType(MetricType.CONCURRENT_GAUGE)
            .withName("myconcurrentgauge")
            .withDescription("awesome")
            .withUnit("dollars") // this should get ignored and should not be reflected in the output
            .build();
    Tag blueTag = new Tag("color", "blue");
    ConcurrentGauge blueCGauge = registry.concurrentGauge(metadata, blueTag);
    Tag greenTag = new Tag("color", "green");
    ConcurrentGauge greenCGauge = registry.concurrentGauge(metadata, greenTag);

    blueCGauge.inc();
    blueCGauge.inc();
    greenCGauge.inc();

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

    assertHasTypeLineExactlyOnce(result, "application_myconcurrentgauge_current", "gauge");
    assertHasTypeLineExactlyOnce(result, "application_myconcurrentgauge_min", "gauge");
    assertHasTypeLineExactlyOnce(result, "application_myconcurrentgauge_max", "gauge");
    assertHasHelpLineExactlyOnce(result, "application_myconcurrentgauge_current", "awesome");

    assertHasValueLineExactlyOnce(result, "application_myconcurrentgauge_current", "2.0", blueTag);
    assertHasValueLineExactlyOnce(result, "application_myconcurrentgauge_current", "1.0", greenTag);
}
 
Example #12
Source File: JaxRsMetricsTestCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTakingArray() {
    when()
            .get("/a/b/c/array")
            .then()
            .statusCode(200);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "array_javax.ws.rs.core.PathSegment[]"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example #13
Source File: KeycloakMetrics.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
/**
 * Increase the number of failed registered users attemps
 *
 * @param keycloakEvent RegisterError event
 */
@Override
public void recordRegistrationError(KeycloakEvent keycloakEvent) {

    Event event = keycloakEvent.getEvent();
    String provider = getIdentityProvider(event);

    Tag[] tags = {
            tag(TAG_REALM, keycloakEvent.getRealmName()),
            tag(TAG_PROVIDER, provider),
            tag(TAG_CLIENT_ID, event.getClientId())
    };

    metricsRegistry.counter(totalRegistrationsErrors, tags).inc();
}
 
Example #14
Source File: JaegerProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void produceMetrics(BuildProducer<MetricBuildItem> producer) {
    producer.produce(
            metric("jaeger_tracer_baggage_restrictions_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(
            metric("jaeger_tracer_baggage_restrictions_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_baggage_truncations", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_baggage_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_baggage_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_finished_spans", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "dropped")));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_queries", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_sampler_queries", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_span_context_decoding_errors", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_started_spans", MetricType.COUNTER, null, new Tag("sampled", "n")));
    producer.produce(metric("jaeger_tracer_started_spans", MetricType.COUNTER, null, new Tag("sampled", "y")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "y"), new Tag("state", "joined")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "y"), new Tag("state", "started")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "n"), new Tag("state", "joined")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "n"), new Tag("state", "started")));
    producer.produce(
            metric("jaeger_tracer_reporter_queue_length", MetricType.GAUGE, new QuarkusJaegerMetricsFactory.JaegerGauge()));
}
 
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: MetricRegistryThreadSafetyTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
}
 
Example #17
Source File: JmxRegistrarTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReplaceMultipleWildcards() {
    assertThat(getMetadataCalled("test_key")).hasSize(1);

    final ExtendedMetadataAndTags extendedMetadata = getSingleMatch("test_key");
    assertThat(extendedMetadata.getMetadata().getName()).isEqualTo("test_key");
    assertThat(extendedMetadata.getMetadata().getDescription()).isEqualTo("Description %s1-%s2");
    assertThat(extendedMetadata.getMetadata().getDisplayName()).isEqualTo("Display Name %s1-%s2");
    assertThat(extendedMetadata.getMetadata().getMbean()).isEqualTo("java.nio:name=%s2,type=%s1/ObjectName");
    assertThat(extendedMetadata.getTags()).contains(
            new Tag("type", "%s1"),
            new Tag("name", "%s2"));
    assertThat(extendedMetadata.getMetadata().getType()).isEqualTo("counter");
    assertThat(extendedMetadata.getMetadata().getUnit()).isEqualTo("none");

    final List<ExtendedMetadataAndTags> metadataList = Lists.list(extendedMetadata);

    JmxWorker.instance().expandMultiValueEntries(metadataList);

    final ExtendedMetadataAndTags extendedMetadata1 = metadataList.get(0);
    assertThat(extendedMetadata1.getMetadata().getDescription()).isEqualTo("Description BufferPool-mapped");
    assertThat(extendedMetadata1.getMetadata().getDisplayName()).isEqualTo("Display Name BufferPool-mapped");
    assertThat(extendedMetadata1.getMetadata().getMbean()).isEqualTo("java.nio:name=mapped,type=BufferPool/ObjectName");
    assertThat(extendedMetadata1.getTags()).contains(
            new Tag("type", "BufferPool"),
            new Tag("name", "mapped"));

    final ExtendedMetadataAndTags extendedMetadata2 = metadataList.get(1);
    assertThat(extendedMetadata2.getMetadata().getDescription()).isEqualTo("Description BufferPool-direct");
    assertThat(extendedMetadata2.getMetadata().getDisplayName()).isEqualTo("Display Name BufferPool-direct");
    assertThat(extendedMetadata2.getMetadata().getMbean()).isEqualTo("java.nio:name=direct,type=BufferPool/ObjectName");
    assertThat(extendedMetadata2.getTags()).contains(
            new Tag("type", "BufferPool"),
            new Tag("name", "direct"));
}
 
Example #18
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testSemicolonInTagValue() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    registry.counter("counter1",
            new Tag("tag1", "i;have;semicolons"),
            new Tag("tag2", "i;have;semicolons;as;well"));

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

    assertNotNull("Semicolons in tag values should be converted to underscores",
            json.getJsonNumber("counter1;tag1=i_have_semicolons;tag2=i_have_semicolons_as_well"));
}
 
Example #19
Source File: TagsUtils.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
public static Tag[] parseTagsAsArray(String[] kvStrings) {
    Tag[] result = new Tag[kvStrings.length];
    int i = 0;
    for (String kvString : kvStrings) {
        result[i] = parseTag(kvString);
        i++;
    }
    return result;
}
 
Example #20
Source File: TagsUtils.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
public static Tag parseTag(String kvString) {
    if (kvString == null || kvString.isEmpty() || !kvString.contains("=")) {
        throw SmallRyeMetricsMessages.msg.notAKeyValuePair(kvString);
    }
    String[] kv = kvString.split("=");
    if (kv.length != 2) {
        throw SmallRyeMetricsMessages.msg.notAKeyValuePair(kvString);
    }
    String key = kv[0].trim();
    String value = kv[1].trim();
    return new Tag(key, value);
}
 
Example #21
Source File: MongoMetricsConnectionPoolListener.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void registerGauge(String metricName, String description, Tag[] tags) {
    getMetricRegistry().remove(new MetricID(metricName, tags));

    Metadata metaData = Metadata.builder().withName(metricName).withType(MetricType.GAUGE)
            .withDescription(description).build();
    getMetricRegistry().register(metaData, new ConnectionPoolGauge(), tags);
}
 
Example #22
Source File: KeycloakMetrics.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
/**
 * Increase the number of currently logged in users
 *
 * @param keycloakEvent Login event
 */
@Override
public void recordLogin(KeycloakEvent keycloakEvent) {

    Event event = keycloakEvent.getEvent();
    String provider = getIdentityProvider(event);

    Tag[] tags = {
            tag(TAG_REALM, keycloakEvent.getRealmName()),
            tag(TAG_PROVIDER, provider),
            tag(TAG_CLIENT_ID, event.getClientId())
    };

    metricsRegistry.counter(totalLogins, tags).inc();
}
 
Example #23
Source File: RestMetricsInterceptor.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
synchronized void init() {
    // Total counter
    final Metadata m1 = Metadata.builder()
            .withName(REST_REQUEST_COUNT)
            .withDescription(REST_REQUEST_COUNT_DESC + " Across all endpoints.")
            .withType(COUNTER)
            .build();
    final Tag[] tags1 = {new Tag("group", REST_GROUP_TAG), new Tag("metric", REST_REQUEST_COUNT)};
    counter = metricRegistry.counter(m1, tags1);
    // Concurrent gauge
    final Metadata m2 = Metadata.builder()
            .withName(REST_CONCURRENT_REQUEST_COUNT)
            .withDescription(REST_CONCURRENT_REQUEST_COUNT_DESC + " Across all endpoints.")
            .withType(CONCURRENT_GAUGE)
            .build();
    final Tag[] tags2 = {new Tag("group", REST_GROUP_TAG), new Tag("metric", REST_CONCURRENT_REQUEST_COUNT)};
    gauge = metricRegistry.concurrentGauge(m2, tags2);
    // Timer
    final Metadata m3 = Metadata.builder()
            .withName(REST_REQUEST_RESPONSE_TIME)
            .withDescription(REST_REQUEST_RESPONSE_TIME_DESC + " Across all endpoints.")
            .withType(TIMER)
            .withUnit(MILLISECONDS)
            .build();
    final Tag[] tags3 = {new Tag("group", REST_GROUP_TAG), new Tag("metric", REST_REQUEST_RESPONSE_TIME)};
    timer = metricRegistry.timer(m3, tags3);

    init = true;
}
 
Example #24
Source File: JaxRsMetricsTestCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodThrowingException() {
    when()
            .get("/exception")
            .then()
            .statusCode(500);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "exception"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example #25
Source File: JsonMetadataExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void exportByScopeWithMultipleMetrics() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1", new Tag("key1", "value1"));
    applicationRegistry.counter("counter1", new Tag("key1", "value2"));
    applicationRegistry.counter("counter2", new Tag("color", "red"));

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

    // check items for counter1
    JsonArray outerTagsArray = json.getJsonObject("counter1").getJsonArray("tags");
    assertEquals(2, outerTagsArray.size());

    JsonArray innerArray1 = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray1.size());
    assertEquals("key1=value1", innerArray1.getString(0));

    JsonArray innerArray2 = outerTagsArray.getJsonArray(1);
    assertEquals(1, innerArray2.size());
    assertEquals("key1=value2", innerArray2.getString(0));

    // check items for counter2
    outerTagsArray = json.getJsonObject("counter2").getJsonArray("tags");
    assertEquals(1, outerTagsArray.size());

    innerArray1 = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray1.size());
    assertEquals("color=red", innerArray1.getString(0));
}
 
Example #26
Source File: JsonMetadataExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void exportByMetricNameWithOneMetricSingleTag() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1", new Tag("key1", "value1"));

    String result = exporter.exportMetricsByName(MetricRegistry.Type.APPLICATION, "counter1").toString();

    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();
    JsonArray outerTagsArray = json.getJsonObject("counter1").getJsonArray("tags");
    assertEquals(1, outerTagsArray.size());
    JsonArray innerArray = outerTagsArray.getJsonArray(0);
    assertEquals(1, innerArray.size());
    assertEquals("key1=value1", innerArray.getString(0));
}
 
Example #27
Source File: JaxRsMetricsTestCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() {
    when()
            .get("/hello/joe")
            .then()
            .statusCode(200);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "hello_java.lang.String"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example #28
Source File: JaxRsMetricsTestCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTakingList() {
    when()
            .get("/a/b/c/list")
            .then()
            .statusCode(200);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "list_java.util.List"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example #29
Source File: JaxRsMetricsTestCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodReturningServerError() throws InterruptedException {
    when()
            .get("/error")
            .then()
            .statusCode(500);
    SimpleTimer metric = metricRegistry.simpleTimer("REST.request",
            new Tag("class", METRIC_RESOURCE_CLASS_NAME),
            new Tag("method", "error"));
    assertEquals(1, metric.getCount());
    assertTrue(metric.getElapsedTime().toNanos() > 0);
}
 
Example #30
Source File: RegistrationCornerCasesTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void ambiguousClassButTypeIsProvidedDuringRegistrationWithTags() {
    Metadata metadata = Metadata.builder()
            .withType(MetricType.COUNTER)
            .withName("test")
            .build();
    // the Ambiguous class can be a counter as well as gauge, but we specified the type in the metadata
    // so it should be registered as a counter
    registry.register(metadata, new Ambiguous(), new Tag("a", "b"));

    Assert.assertEquals(MetricType.COUNTER, registry.getMetadata("test").getTypeRaw());
    Assert.assertEquals(666L, registry.getCounter(new MetricID("test", new Tag("a", "b"))).getCount());
}