org.eclipse.microprofile.metrics.MetricRegistry Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.MetricRegistry. 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 7 votes vote down vote up
/**
 * Given a Gauge with unit=dollars (custom unit),
 * check that the statistics from OpenMetricsExporter will be presented in dollars.
 */
@Test
public void gauge_customUnit_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("gauge1")
            .withType(MetricType.GAUGE)
            .withUnit("dollars")
            .build();
    Gauge<Long> gaugeInstance = () -> 3L;
    registry.register(metadata, gaugeInstance);

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

    Assert.assertThat(exported, containsString("application_gauge1_dollars 3.0"));
}
 
Example #2
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void exportGauges() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = Metadata
            .builder()
            .withType(MetricType.GAUGE)
            .withName("mygauge")
            .withDescription("awesome")
            .build();
    Tag blueTag = new Tag("color", "blue");
    registry.register(metadata, (Gauge<Long>) () -> 42L, blueTag);
    Tag greenTag = new Tag("color", "green");
    registry.register(metadata, (Gauge<Long>) () -> 26L, greenTag);

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

    assertHasTypeLineExactlyOnce(result, "application_mygauge", "gauge");
    assertHasHelpLineExactlyOnce(result, "application_mygauge", "awesome");

    assertHasValueLineExactlyOnce(result, "application_mygauge", "42.0", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mygauge", "26.0", greenTag);
}
 
Example #3
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void runtimeMetrics(MetricRegistry registry) {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    Metadata meta = Metadata.builder()
            .withName(JVM_UPTIME)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.MILLISECONDS)
            .withDisplayName("JVM Uptime")
            .withDescription("Displays the time from the start of the Java virtual machine in milliseconds.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return runtimeMXBean.getUptime();
        }
    });
}
 
Example #4
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentHistogramImplementations() {

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

    // the export should behave identical for any class derived from Histogram
    Histogram[] histograms = { new HistogramImpl(new ExponentiallyDecayingReservoir()), new SomeHistogram() };
    int idx = 0;
    for (Histogram h : histograms) {
        String name = "histo_" + idx++;
        applicationRegistry.register(name, h);
        StringBuilder out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name));
        assertNotNull(out);
        System.out.println(out.toString());
        List<String> lines = Arrays.asList(out.toString().split(LINE_SEPARATOR));
        assertEquals(1, lines.stream().filter(line -> line.contains("\"" + name + "\"")).count());
        assertEquals(1, lines.stream().filter(line -> line.contains("\"count\": 0")).count());
    }
}
 
Example #5
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Timer with unit=MINUTES,
 * check that the statistics from OpenMetricsExporter will be correctly converted to SECONDS.
 */
@Test
public void timer_openMetrics() {
    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));

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

    Assert.assertThat(exported, containsString("application_timer1_seconds{quantile=\"0.5\"} 7200.0"));
    Assert.assertThat(exported, containsString("application_timer1_mean_seconds 7200.0"));
    Assert.assertThat(exported, containsString("application_timer1_min_seconds 3600.0"));
    Assert.assertThat(exported, containsString("application_timer1_max_seconds 10800.0"));
}
 
Example #6
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder exportOneMetric(MetricRegistry.Type scope, MetricID metricID) {
    MetricRegistry registry = MetricRegistries.get(scope);
    Map<MetricID, Metric> metricMap = registry.getMetrics();
    Map<String, Metadata> metadataMap = registry.getMetadata();

    Metric m = metricMap.get(metricID);

    Map<MetricID, Metric> outMap = new HashMap<>(1);
    outMap.put(metricID, m);

    JsonObjectBuilder root = JsonProviderHolder.get().createObjectBuilder();
    exportMetricsForMap(outMap, metadataMap)
            .forEach(root::add);
    return stringify(root.build());
}
 
Example #7
Source File: CircuitBreakerFailOnMetricsTest.java    From smallrye-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@Test
public void test(PingService pingService, MetricRegistry metrics) {
    for (int i = 0; i < 10; i++) {
        try {
            pingService.ping();
        } catch (IllegalArgumentException | IllegalStateException expected) {
        }
    }

    assertEquals(5, metrics.counter(
            "ft.io.smallrye.faulttolerance.circuitbreaker.failon.metrics.PingService.ping.circuitbreaker.callsSucceeded.total")
            .getCount());
    assertEquals(5, metrics.counter(
            "ft.io.smallrye.faulttolerance.circuitbreaker.failon.metrics.PingService.ping.circuitbreaker.callsFailed.total")
            .getCount());
    assertEquals(10,
            metrics.counter(
                    "ft.io.smallrye.faulttolerance.circuitbreaker.failon.metrics.PingService.ping.invocations.failed.total")
                    .getCount());
    assertEquals(10,
            metrics.counter(
                    "ft.io.smallrye.faulttolerance.circuitbreaker.failon.metrics.PingService.ping.invocations.total")
                    .getCount());
}
 
Example #8
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 #9
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testUptimeGaugeUnitConversion() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry baseRegistry = MetricRegistries.get(MetricRegistry.Type.BASE);

    Gauge gauge = new MGaugeImpl(JmxWorker.instance(), "java.lang:type=Runtime/Uptime");
    Metadata metadata = new ExtendedMetadata("jvm.uptime", "display name", "description", MetricType.GAUGE, "milliseconds");
    baseRegistry.register(metadata, gauge);

    long actualUptime /* in ms */ = ManagementFactory.getRuntimeMXBean().getUptime();
    double actualUptimeInSeconds = actualUptime / 1000.0;

    StringBuilder out = exporter.exportOneMetric(MetricRegistry.Type.BASE, new MetricID("jvm.uptime"));
    assertNotNull(out);

    double valueFromOpenMetrics = -1;
    for (String line : out.toString().split(System.getProperty("line.separator"))) {
        if (line.startsWith("base_jvm_uptime_seconds")) {
            valueFromOpenMetrics /* in seconds */ = Double
                    .valueOf(line.substring("base:jvm_uptime_seconds".length()).trim());
        }
    }
    assertTrue("Value should not be -1", valueFromOpenMetrics != -1);
    assertTrue(valueFromOpenMetrics >= actualUptimeInSeconds);
}
 
Example #10
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentTimerImplementations() {

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

    // the export should behave identical for any class derived from Timer
    Timer[] timers = { new TimerImpl(), new SomeTimer() };
    int idx = 0;
    for (Timer t : timers) {
        String name = "json_timer_" + idx++;
        applicationRegistry.register(name, t);
        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 #11
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Gauge with unit=MINUTES,
 * check that the statistics from OpenMetricsExporter will be presented in SECONDS.
 */
@Test
public void gauge_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("gauge1")
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Gauge<Long> gaugeInstance = () -> 3L;
    registry.register(metadata, gaugeInstance);

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

    Assert.assertThat(exported, containsString("application_gauge1_seconds 180.0"));
}
 
Example #12
Source File: OpenMetricsExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private void writeSnapshotQuantiles(StringBuilder sb, MetricRegistry.Type scope, Metadata md, Snapshot snapshot,
        String unit,
        boolean performScaling, Map<String, String> tags) {
    Map<String, String> map = copyMap(tags);
    map.put(QUANTILE, "0.5");
    writeValueLine(sb, scope, unit, snapshot.getMedian(), md, map, performScaling);
    map.put(QUANTILE, "0.75");
    writeValueLine(sb, scope, unit, snapshot.get75thPercentile(), md, map, performScaling);
    map.put(QUANTILE, "0.95");
    writeValueLine(sb, scope, unit, snapshot.get95thPercentile(), md, map, performScaling);
    map.put(QUANTILE, "0.98");
    writeValueLine(sb, scope, unit, snapshot.get98thPercentile(), md, map, performScaling);
    map.put(QUANTILE, "0.99");
    writeValueLine(sb, scope, unit, snapshot.get99thPercentile(), md, map, performScaling);
    map.put(QUANTILE, "0.999");
    writeValueLine(sb, scope, unit, snapshot.get999thPercentile(), md, map, performScaling);
}
 
Example #13
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 #14
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 #15
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public void registerMetricFromProducer(String beanId, MetricType metricType,
        String metricName, String[] tags, String description,
        String displayName, String unit) {
    ArcContainer container = Arc.container();
    InjectableBean<Object> injectableBean = container.bean(beanId);
    BeanManager beanManager = container.beanManager();
    Metric reference = (Metric) beanManager.getReference(injectableBean, Metric.class,
            beanManager.createCreationalContext(injectableBean));
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withType(metricType)
            .withName(metricName)
            .withDescription(description)
            .withDisplayName(displayName)
            .withUnit(unit)
            .notReusable()
            .build();
    registry.register(metadata, reference, TagsUtils.parseTagsAsArray(tags));
}
 
Example #16
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 #17
Source File: JsonMetadataExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder exportMetricsByName(MetricRegistry.Type scope, String name) {
    MetricRegistry registry = MetricRegistries.get(scope);
    if (registry == null) {
        return null;
    }

    Metadata metadata = registry.getMetadata().get(name);

    if (metadata == null) {
        return null;
    }

    JsonObjectBuilder builder = JsonProviderHolder.get().createObjectBuilder();
    metricJSON(builder, name, metadata, getKnownTagsByMetricName(registry, name));
    return stringify(builder.build());

}
 
Example #18
Source File: JsonMetadataExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void exportByMetricNameWithOneMetricMultipleTags() {
    JsonMetadataExporter exporter = new JsonMetadataExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    applicationRegistry.counter("counter1",
            new Tag("key1", "value1"),
            new Tag("color", "blue"));

    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(2, innerArray.size());
    assertEquals("color=blue", innerArray.getString(0));
    assertEquals("key1=value1", innerArray.getString(1));
}
 
Example #19
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 #20
Source File: MpMetricTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
@InSequence(12)
public void testBaseMetadataTypeAndUnit() {
    Assume.assumeFalse(Boolean.getBoolean("skip.base.metric.tests"));
    Header wantJson = new Header("Accept", APPLICATION_JSON);

    JsonPath jsonPath = given().header(wantJson).options("/metrics/base").jsonPath();

    Map<String, Map<String, Object>> elements = jsonPath.getMap(".");

    Map<String, MiniMeta> expectedMetadata = getExpectedMetadataFromXmlFile(MetricRegistry.Type.BASE);
          checkMetadataPresent(elements, expectedMetadata);

}
 
Example #21
Source File: JsonMetadataExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private JsonObject rootJSON() {
    JsonObjectBuilder root = JsonProviderHolder.get().createObjectBuilder();

    root.add("base", registryJSON(MetricRegistries.get(MetricRegistry.Type.BASE)));
    root.add("vendor", registryJSON(MetricRegistries.get(MetricRegistry.Type.VENDOR)));
    root.add("application", registryJSON(MetricRegistries.get(MetricRegistry.Type.APPLICATION)));

    return root.build();
}
 
Example #22
Source File: MpMetricTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * Check that there is at least one metric named gc.total and that they all contain
 * expected tags (actually this is just 'name' for now).
 */
@Test
@RunAsClient
@InSequence(43)
public void testGcCountMetrics() {
    Assume.assumeFalse(Boolean.getBoolean("skip.base.metric.tests"));
    Header wantJson = new Header("Accept", APPLICATION_JSON);
    JsonPath jsonPath = given().header(wantJson).get("/metrics/base").jsonPath();

    Map<String, MiniMeta> baseNames = getExpectedMetadataFromXmlFile(MetricRegistry.Type.BASE);
    MiniMeta gcCountMetricMeta = baseNames.get("gc.total");
    Set<String> expectedTags = gcCountMetricMeta.tags.keySet();

    // obtain list of actual base metrics from the runtime and find all named gc.total
    Map<String, Object> elements = jsonPath.getMap(".");
    boolean found = false;
    for (Map.Entry<String, Object> metricEntry : elements.entrySet()) {
        if(metricEntry.getKey().startsWith("gc.total")) {
            // We found a metric named gc.total. Now check that it contains all expected tags
            for(String expectedTag : expectedTags) {
                assertThat("The metric should contain a " + expectedTag + " tag",
                    metricEntry.getKey(), containsString(expectedTag + "="));
            }
            // check that the metric has a reasonable value - it should at least be numeric and not negative
            Assert.assertTrue("gc.total value should be numeric",
                metricEntry.getValue() instanceof Number);
            Assert.assertTrue("gc.total value should not be a negative number",
                (Integer)metricEntry.getValue() >= 0);
            found = true;
        }
    }
    Assert.assertTrue("At least one metric named gc.total is expected", found);
}
 
Example #23
Source File: JsonMetadataExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder exportOneScope(MetricRegistry.Type scope) {
    MetricRegistry registry = MetricRegistries.get(scope);
    if (registry == null) {
        return null;
    }

    JsonObject obj = registryJSON(registry);
    return stringify(obj);
}
 
Example #24
Source File: JsonMetadataExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
/**
 * Find all currently existing metrics under this name in this registry and
 * for each of them, convert its tags to a list of strings.
 * Return a list of all these lists (so one item in the outer list will correspond to a metric,
 * one item in each of the inner lists will correspond to a tag pertaining to that metric)
 */
private List<List<String>> getKnownTagsByMetricName(MetricRegistry registry, String name) {
    return registry.getMetricIDs()
            .stream()
            .filter(id -> id.getName().equals(name))
            .map(id -> id.getTagsAsList()
                    .stream()
                    .map(tag -> tag.getTagName() + "=" + tag.getTagValue())
                    .collect(Collectors.toList()))
            .collect(Collectors.toList());
}
 
Example #25
Source File: SeMetricName.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public String of(AnnotatedMember<?> member) {
    if (member.isAnnotationPresent(Metric.class)) {
        Metric metric = member.getAnnotation(Metric.class);
        String name = (metric.name().isEmpty()) ? member.getJavaMember().getName() : of(metric.name());
        return metric.absolute() | parameters.contains(MetricsParameter.useAbsoluteName) ? name
                : MetricRegistry.name(member.getJavaMember().getDeclaringClass(), name);
    } else {
        return parameters.contains(MetricsParameter.useAbsoluteName) ? member.getJavaMember().getName()
                : MetricRegistry.name(member.getJavaMember().getDeclaringClass(), member.getJavaMember().getName());
    }
}
 
Example #26
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 #27
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewlineCharacterInTagValue() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

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

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

    assertEquals("Newline chars in tag values should be escaped as \\n",
            "counter1;tag1=i_have\n_two_lines", json.keySet().stream().findFirst().get());
}
 
Example #28
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testHelpLineQuoting() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = Metadata.builder()
            .withName("counter_with_complicated_description")
            .withDescription("hhh\\ggg\\nfff\\").build();
    registry.counter(metadata);
    String export = exporter
            .exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("counter_with_complicated_description"))
            .toString();

    // hhh\ggg\nfff\ should become hhh\\ggg\nfff\\
    assertThat(export,
            containsString("# HELP application_counter_with_complicated_description_total hhh\\\\ggg\\nfff\\\\"));

    metadata = Metadata.builder()
            .withName("counter_with_complicated_description_2")
            .withDescription("description with \"quotes\"").build();
    registry.counter(metadata);
    export = exporter
            .exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID("counter_with_complicated_description_2"))
            .toString();

    // double quotes should stay unchanged
    assertThat(export,
            containsString("# HELP application_counter_with_complicated_description_2_total description with \"quotes\""));
}
 
Example #29
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrentGauges() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    ConcurrentGauge cGaugeWithoutTags = registry.concurrentGauge("mycgauge");
    ConcurrentGauge cGaugeRed = registry.concurrentGauge("mycgauge", new Tag("color", "red"));
    ConcurrentGauge cGaugeBlue = registry.concurrentGauge("mycgauge", new Tag("color", "blue"), new Tag("foo", "bar"));

    cGaugeWithoutTags.inc();
    cGaugeRed.inc();
    cGaugeRed.inc();
    cGaugeBlue.inc();
    cGaugeBlue.inc();
    cGaugeBlue.inc();

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

    JsonObject myCgaugeObject = json.getJsonObject("mycgauge");

    assertEquals(1, myCgaugeObject.getInt("current"));
    assertEquals(2, myCgaugeObject.getInt("current;color=red"));
    assertEquals(3, myCgaugeObject.getInt("current;color=blue;foo=bar"));

    assertNotNull(myCgaugeObject.getJsonNumber("min"));
    assertNotNull(myCgaugeObject.getJsonNumber("min;color=red"));
    assertNotNull(myCgaugeObject.getJsonNumber("min;color=blue;foo=bar"));

    assertNotNull(myCgaugeObject.getJsonNumber("max"));
    assertNotNull(myCgaugeObject.getJsonNumber("max;color=red"));
    assertNotNull(myCgaugeObject.getJsonNumber("max;color=blue;foo=bar"));
}
 
Example #30
Source File: OpenMetricsExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder exportMetricsByName(MetricRegistry.Type scope, String name) {
    alreadyExportedNames.set(new HashSet<>());
    MetricRegistry registry = MetricRegistries.get(scope);
    Map<MetricID, Metric> metricsToExport = registry.getMetrics()
            .entrySet()
            .stream()
            .filter(entry -> entry.getKey().getName().equals(name))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    StringBuilder sb = new StringBuilder();
    exposeEntries(scope, sb, registry, metricsToExport);
    alreadyExportedNames.set(null);
    return sb;
}