org.eclipse.microprofile.metrics.Gauge Java Examples

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

    Gauge<Long> gaugeWithoutTags = () -> 1L;
    Gauge<Long> gaugeRed = () -> 2L;
    Gauge<Long> gaugeBlue = () -> 3L;

    final Metadata metadata = new MetadataBuilder()
            .withType(MetricType.GAUGE)
            .withName("mygauge")
            .build();

    registry.register(metadata, gaugeWithoutTags);
    registry.register(metadata, gaugeRed, new Tag("color", "red"));
    registry.register(metadata, gaugeBlue, new Tag("color", "blue"), new Tag("foo", "bar"));

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

    assertEquals(1, json.getInt("mygauge"));
    assertEquals(2, json.getInt("mygauge;color=red"));
    assertEquals(3, json.getInt("mygauge;color=blue;foo=bar"));
}
 
Example #3
Source File: GaugeTagMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(1)
public void gaugeTagCalledWithDefaultValue() {

    @SuppressWarnings("unchecked")
    Gauge<Long> gaugeOne = (Gauge<Long>) registry.getGauge(gaugeOneMID);

    @SuppressWarnings("unchecked")
    Gauge<Long> gaugeTwo = (Gauge<Long>) registry.getGauge(gaugeTwoMID);

    assertThat("Gauge is not registered correctly", gaugeOne, notNullValue());
    assertThat("Gauge is not registered correctly", gaugeTwo, notNullValue());

    // Make sure that the gauge has the expected value
    assertThat("Gauge value is incorrect", gaugeOne.getValue(), is(equalTo(0L)));
    assertThat("Gauge value is incorrect", gaugeTwo.getValue(), is(equalTo(0L)));
}
 
Example #4
Source File: InheritedGaugeMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void callGaugesAfterSetterCalls() {
    @SuppressWarnings("unchecked")
    Gauge<Long> parentGauge = (Gauge<Long>) registry.getGauge(parentMID);
    @SuppressWarnings("unchecked")
    Gauge<Long> childGauge = (Gauge<Long>) registry.getGauge(childMID);
    assertThat("Gauges are not registered correctly", parentGauge, notNullValue());
    assertThat("Gauges are not registered correctly", childGauge, notNullValue());

    // Call the setter methods and assert the gauges are up-to-date
    long parentValue = Math.round(Math.random() * Long.MAX_VALUE);
    pBean.setGauge(parentValue);
    long childValue = Math.round(Math.random() * Long.MAX_VALUE);
    bean.setChildGauge(childValue);
    assertThat("Gauge values are incorrect", Arrays.asList(parentGauge.getValue(), childGauge.getValue()), contains(parentValue, childValue));
}
 
Example #5
Source File: GaugeTagMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void callGaugeTagAfterSetterCall() {
    @SuppressWarnings("unchecked")
    Gauge<Long> gaugeOne = (Gauge<Long>) registry.getGauge(gaugeOneMID);
    @SuppressWarnings("unchecked")
    Gauge<Long> gaugeTwo = (Gauge<Long>) registry.getGauge(gaugeTwoMID);
    assertThat("Gauge is not registered correctly", gaugeOne, notNullValue());
    assertThat("Gauge is not registered correctly", gaugeTwo, notNullValue());

    // Call the setter method and assert the gauge is up-to-date
    long value = Math.round(Math.random() * Long.MAX_VALUE);
    bean.setGaugeOne(value);
    
    long secondValue = Math.round(Math.random() * Long.MAX_VALUE);
    bean.setGaugeTwo(secondValue);
    
    assertThat("Gauge value is incorrect", gaugeOne.getValue(), is(equalTo(value)));
    assertThat("Gauge value is incorrect", gaugeTwo.getValue(), is(equalTo(secondValue)));
}
 
Example #6
Source File: MetricProducerMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void callCachedMethodMultipleTimes() {
    assertThat("Metrics are not registered correctly", registry.getMetricIDs(),
        contains(cacheHitsMID, callsMID, hitsMID));
    Timer calls = registry.getTimer(callsMID);
    Meter hits = registry.getMeter(hitsMID);
    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(cacheHitsMID);

    long count = 10 + Math.round(Math.random() * 10);
    for (int i = 0; i < count; i++) {
        bean.cachedMethod((Math.random() < 0.5));
    }

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo((double) hits.getCount() / (double) calls.getCount())));
}
 
Example #7
Source File: MetricProducerFieldBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(1)
public void countersNotIncrementedYet() {
    assertThat("Counters are not registered correctly", registry.getCounters(),
        allOf(
            hasKey(counter1MID),
            hasKey(counter2MID),
            not(hasKey(notRegMID))
        )
    );
    Counter counter1 = registry.getCounter(counter1MID);
    Counter counter2 = registry.getCounter(counter2MID);

    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(ratioGaugeMID);
    assertThat("Gauge is not registered correctly", gauge, notNullValue());

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) counter1.getCount()) / ((double) counter2.getCount()))));
}
 
Example #8
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 #9
Source File: MetricProducerFieldBeanTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(2)
public void incrementCountersFromRegistry() {
    assertThat("Counters are not registered correctly", registry.getCounters(),
        allOf(
            hasKey(counter1MID),
            hasKey(counter2MID),
            not(hasKey(notRegMID))
        )
    );
    Counter counter1 = registry.getCounter(counter1MID);
    Counter counter2 = registry.getCounter(counter2MID);

    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(ratioGaugeMID);
    assertThat("Gauge is not registered correctly", gauge, notNullValue());

    counter1.inc(Math.round(Math.random() * Integer.MAX_VALUE));
    counter2.inc(Math.round(Math.random() * Integer.MAX_VALUE));

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) counter1.getCount()) / ((double) counter2.getCount()))));
}
 
Example #10
Source File: AgroalMetricsTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testMetricsOfDs1() throws SQLException {
    Counter acquireCount = registry.getCounters().get(new MetricID("agroal.acquire.count",
            new Tag("datasource", "ds1")));
    Gauge<?> maxUsed = registry.getGauges().get(new MetricID("agroal.max.used.count",
            new Tag("datasource", "ds1")));
    Assertions.assertNotNull(acquireCount, "Agroal metrics should be registered eagerly");
    Assertions.assertNotNull(maxUsed, "Agroal metrics should be registered eagerly");

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

    Assertions.assertEquals(1L, acquireCount.getCount());
    Assertions.assertEquals(1L, maxUsed.getValue());
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
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 MINUTES.
 */
@Test
public void gauge_json() {
    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);

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

    JsonObject json = Json.createReader(new StringReader(exported)).read().asJsonObject();
    assertEquals(3, json.getInt("gauge1"));
}
 
Example #16
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 #17
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private boolean isSameType(Metric metricInstance, MetricType type) {
    switch (type) {
        case CONCURRENT_GAUGE:
            return metricInstance instanceof ConcurrentGauge;
        case GAUGE:
            return metricInstance instanceof Gauge;
        case HISTOGRAM:
            return metricInstance instanceof Histogram;
        case TIMER:
            return metricInstance instanceof Timer;
        case METERED:
            return metricInstance instanceof Meter;
        case COUNTER:
            return metricInstance instanceof Counter;
        case SIMPLE_TIMER:
            return metricInstance instanceof SimpleTimer;
        default:
            throw new IllegalArgumentException();
    }
}
 
Example #18
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private MetricType metricTypeFromClass(Class<?> in) {
    if (in.equals(Counter.class)) {
        return MetricType.COUNTER;
    } else if (in.equals(Gauge.class)) {
        return MetricType.GAUGE;
    } else if (in.equals(ConcurrentGauge.class)) {
        return MetricType.CONCURRENT_GAUGE;
    } else if (in.equals(Meter.class)) {
        return MetricType.METERED;
    } else if (in.equals(Timer.class)) {
        return MetricType.TIMER;
    } else if (in.equals(SimpleTimer.class)) {
        return MetricType.SIMPLE_TIMER;
    } else if (in.equals(Histogram.class)) {
        return MetricType.HISTOGRAM;
    }
    return null;
}
 
Example #19
Source File: MetricGetter.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@code baseline()} on all relevant metrics.
 * <p>
 * Extracts all of the {@code Counter} and {@code Gauge} metrics from
 * {@link MetricDefinition} and calls {@link CounterMetric#baseline()} or
 * {@link GaugeMetric#baseline()} on them.
 * <p>
 * This allows us to check how they've changed later in the test using the
 * {@code CounterMetric.delta()} or {@code GaugeMetric.delta()} methods, without
 * having to explicitly baseline every metric ourselves up front.
 */
public void baselineMetrics() {
    for (MetricDefinition definition : MetricDefinition.values()) {
        for (TagValue[] tags : getTagCombinations(definition.getTagClasses())) {
            MetricID id = getMetricId(definition, tags);
            if (definition.getMetricClass() == Counter.class) {
                getCounterMetric(id).baseline();
            }
            if (definition.getMetricClass() == Gauge.class) {
                getGaugeMetric(id).baseline();
            }
        }
    }
}
 
Example #20
Source File: GaugeTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testManualGauge() {
    MetricID gaugeMetricID = new MetricID("tck.gaugetest.gaugemanual");
    
    Gauge<?> gauge = metrics.getGauge(gaugeMetricID);
    Assert.assertNull(gauge);
    gaugeMe();
    gauge = metrics.getGauge(gaugeMetricID);
    
    Assert.assertEquals(0, gauge.getValue());
    Assert.assertEquals(1, gauge.getValue());
}
 
Example #21
Source File: GaugeMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(2)
public void callGaugeAfterSetterCall() {
    @SuppressWarnings("unchecked")
    Gauge<Long> gauge = (Gauge<Long>) registry.getGauge(gaugeMID);
    assertThat("Gauge is not registered correctly", gauge, notNullValue());

    // Call the setter method and assert the gauge is up-to-date
    long value = Math.round(Math.random() * Long.MAX_VALUE);
    bean.setGauge(value);
    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(value)));
}
 
Example #22
Source File: GaugeMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void gaugeCalledWithDefaultValue() {
    @SuppressWarnings("unchecked")
    Gauge<Long> gauge = (Gauge<Long>) registry.getGauge(gaugeMID);
    assertThat("Gauge is not registered correctly", gauge, notNullValue());

    // Make sure that the gauge has the expected value
    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(0L)));
}
 
Example #23
Source File: MetricsCollectorFactory.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
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 #24
Source File: InheritedGaugeMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void gaugesCalledWithDefaultValues() {
    @SuppressWarnings("unchecked")
    Gauge<Long> parentGauge = (Gauge<Long>) registry.getGauge(parentMID);
    @SuppressWarnings("unchecked")
    Gauge<Long> childGauge = (Gauge<Long>) registry.getGauge(childMID);
    assertThat("Gauges are not registered correctly", parentGauge, notNullValue());
    assertThat("Gauges are not registered correctly", childGauge, notNullValue());

    // Make sure that the gauge has the expected value
    assertThat("Gauge values are incorrect", Arrays.asList(parentGauge.getValue(), childGauge.getValue()), contains(0L, 0L));
}
 
Example #25
Source File: SmallRyeMetricsRecorder.java    From quarkus with 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 #26
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Mimics Uptime metrics from Micrometer. Most of the logic here is basically copied from
 * {@link <a href=
 * "https://github.com/micrometer-metrics/micrometer/blob/master/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/system/UptimeMetrics.java">Micrometer
 * Uptime metrics</a>}.
 * 
 * @param registry
 */
private void micrometerRuntimeMetrics(MetricRegistry registry) {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("process.runtime")
                    .withType(MetricType.GAUGE)
                    .withUnit(MetricUnits.MILLISECONDS)
                    .withDescription("The uptime of the Java virtual machine")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return runtimeMXBean.getUptime();
                }
            });
    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("process.start.time")
                    .withType(MetricType.GAUGE)
                    .withUnit(MetricUnits.MILLISECONDS)
                    .withDescription("Start time of the process since unix epoch.")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return runtimeMXBean.getStartTime();
                }
            });
}
 
Example #27
Source File: MetricProducerMethodBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Test
@InSequence(1)
public void cachedMethodNotCalledYet() {
    assertThat("Metrics are not registered correctly", registry.getMetricIDs(),
        contains(cacheHitsMID, callsMID, hitsMID));
    Timer calls = registry.getTimer(callsMID);
    Meter hits = registry.getMeter(hitsMID);
    @SuppressWarnings("unchecked")
    Gauge<Double> gauge = (Gauge<Double>) registry.getGauge(cacheHitsMID);

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) hits.getCount() / (double) calls.getCount()))));
}
 
Example #28
Source File: MetricProducerMethodBean.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Produces
@Metric(name = "cache-hits")
Gauge<Double> cacheHitRatioGauge(final @Metric(name = "hits") Meter hits, final @Metric(name = "calls") Timer calls) {
    return new Gauge<Double>() {

        @Override
        public Double getValue() {
            return (double) hits.getCount() / (double) calls.getCount();
        }
    };

}
 
Example #29
Source File: MetricAppBean.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
public void gaugeMe() {

        @SuppressWarnings("unchecked")
        Gauge<Long> gauge = (Gauge<Long>) metrics.getGauge(new MetricID("metricTest.test1.gauge"));
        if (gauge == null) {
            gauge = () -> {
                return 19L;
            };

            Metadata metadata = Metadata.builder().withName("metricTest.test1.gauge")
                    .withType(MetricType.GAUGE).withUnit(MetricUnits.GIGABYTES).build();
            metrics.register(metadata, gauge);
        }

    }
 
Example #30
Source File: MetricProducerFieldBeanTest.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@InSequence(3)
public void incrementCountersFromInjection(@Metric(name = "ratioGauge", absolute = true) Gauge<Double> gauge,
                                           @Metric(name = "counter1", absolute = true) Counter counter1,
                                           @Metric(name = "counter2", absolute = true) Counter counter2) {
    counter1.inc(Math.round(Math.random() * Integer.MAX_VALUE));
    counter2.inc(Math.round(Math.random() * Integer.MAX_VALUE));

    assertThat("Gauge value is incorrect", gauge.getValue(), is(equalTo(((double) counter1.getCount()) / ((double) counter2.getCount()))));

    @SuppressWarnings("unchecked")
    Gauge<Double> gaugeFromRegistry = (Gauge<Double>) registry.getGauge(new MetricID("ratioGauge"));
    assertThat("Gauge is not registered correctly", gaugeFromRegistry, notNullValue());

    assertThat("Gauge values from registry and injection do not match", gauge.getValue(), is(equalTo(gaugeFromRegistry.getValue())));
}