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

The following examples show how to use org.eclipse.microprofile.metrics.MetricRegistry. 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
/**
 * 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 2
Source Project: smallrye-metrics   Source File: JsonMetadataExporterTest.java    License: 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 3
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: 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 4
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: 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 5
@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 6
Source Project: quarkus   Source File: SmallRyeMetricsRecorder.java    License: 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 7
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: 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 8
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: 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 9
/**
 * 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 10
/**
 * 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 11
Source Project: smallrye-metrics   Source File: JsonMetadataExporter.java    License: 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 12
Source Project: smallrye-metrics   Source File: JsonExporter.java    License: 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 13
/**
 * 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 14
/**
 * 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 Project: quarkus   Source File: SmallRyeMetricsRecorder.java    License: 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 16
Source Project: smallrye-metrics   Source File: OpenMetricsExporter.java    License: 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 17
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: 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 18
/**
 * 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 19
Source Project: smallrye-metrics   Source File: JsonMetadataExporterTest.java    License: 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 20
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNewlineCharacterEscaping() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Tag tag = new Tag("a", "b\nc");
    registry.counter("mycounter", tag);

    String result = exporter.exportOneScope(MetricRegistry.Type.APPLICATION).toString();
    assertTrue(result.contains("application_mycounter_total{a=\"b\\nc\"} 0.0"));
}
 
Example 21
Source Project: smallrye-graphql   Source File: GraphQLProducer.java    License: Apache License 2.0 5 votes vote down vote up
public GraphQLSchema initialize() {
    this.graphQLSchema = Bootstrap.bootstrap(schema, graphQLConfig);
    if (graphQLConfig.isMetricsEnabled()) {
        MetricRegistry vendorRegistry = MetricsService.load().getMetricRegistry(MetricRegistry.Type.VENDOR);
        Bootstrap.registerMetrics(schema, vendorRegistry);
    }
    this.executionService = new ExecutionService(graphQLConfig, graphQLSchema);
    this.schemaPrinter = new SchemaPrinter(graphQLConfig);
    return this.graphQLSchema;
}
 
Example 22
Source Project: liberty-bikes   Source File: GameMetrics.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private static MetricRegistry getRegistry() {
    try {
        registry = CDI.current().select(MetricRegistry.class).get();
        System.out.println("MetricRegistry configured");
        return registry;
    } catch (IllegalStateException ise) {
        System.out.println("WARNING: Unable to locate CDIProvider");
        ise.printStackTrace();
    }
    return null;
}
 
Example 23
Source Project: smallrye-graphql   Source File: TestMetricsServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MetricRegistry getMetricRegistry(Type type) {
    if (type.equals(Type.VENDOR)) {
        return vendorRegistry;
    }
    return null;
}
 
Example 24
Source Project: smallrye-graphql   Source File: MetricDecoratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() {
    MetricsService service = MetricsService.load();
    service.getMetricRegistry(MetricRegistry.Type.VENDOR);
    TestMetricsServiceImpl.vendorRegistry.simpleTimeMetadatas.clear();
    TestMetricsServiceImpl.vendorRegistry.simpleTimers.clear();
}
 
Example 25
@Test
public void test(MyService service, MetricRegistry metrics) {
    String result = service.hello();
    assertEquals("fallback", result);

    assertEquals(1, metrics.counter(
            "ft.io.smallrye.faulttolerance.fallback.retry.metrics.MyService.hello.invocations.total")
            .getCount());
    assertEquals(0, metrics.counter(
            "ft.io.smallrye.faulttolerance.fallback.retry.metrics.MyService.hello.invocations.failed.total")
            .getCount());

    assertEquals(1, metrics.counter(
            "ft.io.smallrye.faulttolerance.fallback.retry.metrics.MyService.hello.fallback.calls.total")
            .getCount());

    assertEquals(3, metrics.counter(
            "ft.io.smallrye.faulttolerance.fallback.retry.metrics.MyService.hello.retry.retries.total")
            .getCount());
    assertEquals(1, metrics.counter(
            "ft.io.smallrye.faulttolerance.fallback.retry.metrics.MyService.hello.retry.callsFailed.total")
            .getCount());
    assertEquals(0, metrics.counter(
            "ft.io.smallrye.faulttolerance.fallback.retry.metrics.MyService.hello.retry.callsSucceededRetried.total")
            .getCount());
    assertEquals(0, metrics.counter(
            "ft.io.smallrye.faulttolerance.fallback.retry.metrics.MyService.hello.retry.callsSucceededNotRetried.total")
            .getCount());
}
 
Example 26
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAllScopes() {
    JsonExporter exporter = new JsonExporter();
    MetricRegistries.get(MetricRegistry.Type.APPLICATION).counter("c1");
    MetricRegistries.get(MetricRegistry.Type.BASE).counter("b1");
    MetricRegistries.get(MetricRegistry.Type.VENDOR).counter("a1");

    String result = exporter.exportAllScopes().toString();
    JsonObject json = Json.createReader(new StringReader(result)).read().asJsonObject();

    assertEquals(0, json.getJsonObject("application").getInt("c1"));
    assertEquals(0, json.getJsonObject("base").getInt("b1"));
    assertEquals(0, json.getJsonObject("vendor").getInt("a1"));
}
 
Example 27
Source Project: smallrye-metrics   Source File: JmxRegistrar.java    License: Apache License 2.0 5 votes vote down vote up
private void register(String propertiesFile, MetricRegistry registry) throws IOException {
    List<ExtendedMetadataAndTags> configs = findMetadata(propertiesFile);

    for (ExtendedMetadataAndTags config : configs) {
        register(registry, config.getMetadata(), config.getTags());
    }
}
 
Example 28
Source Project: quarkus   Source File: SmallRyeMetricsRecorder.java    License: Apache License 2.0 5 votes vote down vote up
private void micrometerJvmClassLoaderMetrics(MetricRegistry registry) {
    // The ClassLoadingMXBean can be used in native mode, but it only returns zeroes, so there's no point in including such metrics.
    if (!ImageInfo.inImageCode()) {
        ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();

        registry.register(
                new ExtendedMetadataBuilder()
                        .withName("jvm.classes.loaded")
                        .withType(MetricType.GAUGE)
                        .withUnit("classes")
                        .withDescription("The number of classes that are currently loaded in the Java virtual machine")
                        .withOpenMetricsKeyOverride("jvm_classes_loaded_classes")
                        .build(),
                new Gauge() {
                    @Override
                    public Number getValue() {
                        return classLoadingBean.getLoadedClassCount();
                    }
                });

        registry.register(
                new ExtendedMetadataBuilder()
                        .withName("jvm.classes.unloaded")
                        .withType(MetricType.COUNTER)
                        .withUnit("classes")
                        .withDescription(
                                "The total number of classes unloaded since the Java virtual machine has started execution")
                        .withOpenMetricsKeyOverride("jvm_classes_unloaded_classes_total")
                        .build(),
                new GetCountOnlyCounter() {
                    @Override
                    public long getCount() {
                        return classLoadingBean.getUnloadedClassCount();
                    }
                });
    }
}
 
Example 29
Source Project: smallrye-metrics   Source File: MetricRegistries.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
@Default
@RegistryType(type = MetricRegistry.Type.APPLICATION)
@ApplicationScoped
public MetricRegistry getApplicationRegistry() {
    return get(MetricRegistry.Type.APPLICATION);
}
 
Example 30
Source Project: quarkus   Source File: SmallRyeMetricsRecorder.java    License: Apache License 2.0 5 votes vote down vote up
private void garbageCollectionMetrics(MetricRegistry registry) {
    List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans();
    if (gcs.isEmpty()) {
        return;
    }
    Metadata countMetadata = Metadata.builder()
            .withName("gc.total")
            .withType(MetricType.COUNTER)
            .withDisplayName("Garbage Collection Count")
            .withUnit("none")
            .withDescription(
                    "Displays the total number of collections that have occurred. This attribute lists -1 if the collection count is undefined for this collector.")
            .build();
    Metadata timeMetadata = Metadata.builder()
            .withName("gc.time")
            .withType(MetricType.COUNTER)
            .withDisplayName("Garbage Collection Time")
            .withUnit("milliseconds")
            .withDescription(
                    "Displays the approximate accumulated collection elapsed time in milliseconds. This attribute " +
                            "displays -1 if the collection elapsed time is undefined for this collector. The Java " +
                            "virtual machine implementation may use a high resolution timer to measure the " +
                            "elapsed time. This attribute may display the same value even if the collection " +
                            "count has been incremented if the collection elapsed time is very short.")
            .build();
    for (GarbageCollectorMXBean gc : gcs) {
        registry.register(countMetadata, new GetCountOnlyCounter() {
            @Override
            public long getCount() {
                return gc.getCollectionCount();
            }
        }, new Tag("name", gc.getName()));
        registry.register(timeMetadata, new GetCountOnlyCounter() {
            @Override
            public long getCount() {
                return gc.getCollectionTime();
            }
        }, new Tag("name", gc.getName()));
    }
}