org.eclipse.microprofile.metrics.MetricType Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.MetricType. 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: MetricRegistryTest.java    From microprofile-metrics with Apache License 2.0 6 votes vote down vote up
@Test
@InSequence(4)
public void useExistingMetaDataTest() {
    String displayName = "displayCounterFoo";
    String metricName = "counterFoo";

    //first to register a "complex" metadata
    metrics.counter(Metadata.builder().withName(metricName).withDisplayName(displayName).withType(MetricType.COUNTER).build());

    Tag purpleTag = new Tag("colour","purple");
    //creates with a simple/template metadata or uses an existing one.
    metrics.counter(metricName, purpleTag);

    //check both counters have been registered
    assertExists(Counter.class, new MetricID(metricName));
    assertExists(Counter.class, new MetricID(metricName, purpleTag));

    //check that the "original" metadata wasn't replaced by the empty default metadata
    Assert.assertEquals(metrics.getMetadata(metricName).getDisplayName(), displayName);
}
 
Example #2
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 OpenMetricsExporter will be presented in SECONDS.
 */
@Test
public void histogram_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("histogram1")
            .withType(MetricType.HISTOGRAM)
            .withUnit(MetricUnits.MINUTES)
            .build();
    Histogram metric = registry.histogram(metadata);
    metric.update(30);
    metric.update(40);
    metric.update(50);

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

    Assert.assertThat(exported, containsString("application_histogram1_min_seconds 1800.0"));
    Assert.assertThat(exported, containsString("application_histogram1_max_seconds 3000.0"));
    Assert.assertThat(exported, containsString("application_histogram1_mean_seconds 2400.0"));
    Assert.assertThat(exported, containsString("application_histogram1_seconds{quantile=\"0.5\"} 2400.0"));
}
 
Example #3
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 OpenMetricsExporter will not be scaled in any way.
 */
@Test
public void counter_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("counter1")
            .withType(MetricType.COUNTER)
            .build();
    Counter metric = registry.counter(metadata);
    metric.inc(30);
    metric.inc(40);
    metric.inc(50);

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

    Assert.assertThat(exported, containsString("application_counter1_total 120.0"));
}
 
Example #4
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 #5
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 #6
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 JsonExporter will be presented in MINUTES.
 */
@Test
public void timer_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);
    assertEquals(360.0, json.getJsonNumber("elapsedTime").doubleValue(), 0.001);
}
 
Example #7
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 #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: 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 #10
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Guess the metric type from a class object. Recursively scans its
 * superclasses and implemented interfaces.
 * If no metric type can be inferred, returns null.
 * If multiple metric types are inferred, throws an IllegalArgumentException.
 */
private MetricType inferMetricType(Class<?> clazz) {
    MetricType direct = metricTypeFromClass(clazz);
    if (direct != null) {
        return direct;
    } else {
        MetricType candidateType = null;
        // recursively scan the superclass first, then implemented interfaces
        Class<?> superClass = clazz.getSuperclass();
        if (superClass != null && !superClass.equals(Object.class)) {
            candidateType = inferMetricType(superClass);
        }
        for (Class<?> implementedInterface : clazz.getInterfaces()) {
            MetricType newCandidateType = inferMetricType(implementedInterface);
            if (candidateType == null) {
                candidateType = newCandidateType;
            } else {
                if (newCandidateType != null && !candidateType.equals(newCandidateType)) {
                    throw SmallRyeMetricsMessages.msg.ambiguousMetricType(newCandidateType, candidateType);
                }
            }
        }
        return candidateType;
    }
}
 
Example #11
Source File: MemberToMetricMappings.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
public void addMetric(MemberInfo member, MetricID metricID, MetricType metricType) {
    switch (metricType) {
        case COUNTER:
            counters.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case CONCURRENT_GAUGE:
            concurrentGauges.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case METERED:
            meters.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case TIMER:
            timers.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        case SIMPLE_TIMER:
            simpleTimers.computeIfAbsent(member, id -> new HashSet<>()).add(metricID);
            break;
        default:
            throw SmallRyeMetricsMessages.msg.unknownMetricType();
    }
    SmallRyeMetricsLogging.log.matchingMemberToMetric(member, metricID, metricType);
}
 
Example #12
Source File: ExportersMetricScalingTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Histogram with unit=dollars (custom unit),
 * check that the statistics from OpenMetricsExporter will be presented in dollars.
 */
@Test
public void histogram_customunit_openMetrics() {
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withName("histogram1")
            .withType(MetricType.HISTOGRAM)
            .withUnit("dollars")
            .build();
    Histogram metric = registry.histogram(metadata);
    metric.update(30);
    metric.update(40);
    metric.update(50);

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

    Assert.assertThat(exported, containsString("application_histogram1_min_dollars 30.0"));
    Assert.assertThat(exported, containsString("application_histogram1_max_dollars 50.0"));
    Assert.assertThat(exported, containsString("application_histogram1_mean_dollars 40.0"));
    Assert.assertThat(exported, containsString("application_histogram1_dollars{quantile=\"0.5\"} 40.0"));
}
 
Example #13
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 #14
Source File: MeteredInterceptor.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private <E extends Member & AnnotatedElement> Object meteredCallable(InvocationContext context, E element)
        throws Exception {
    Set<MetricID> ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
            .getMeters(new CDIMemberInfoAdapter<>().convert(element));
    if (ids == null || ids.isEmpty()) {
        throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
    }
    ids.stream()
            .map(metricID -> {
                Meter metric = registry.getMeters().get(metricID);
                if (metric == null) {
                    throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.METERED, metricID);
                }
                return metric;
            })
            .forEach(Meter::mark);
    return context.proceed();
}
 
Example #15
Source File: SimplyTimedInterceptor.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private <E extends Member & AnnotatedElement> Object timedCallable(InvocationContext invocationContext, E element)
        throws Exception {
    Set<MetricID> ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
            .getSimpleTimers(new CDIMemberInfoAdapter<>().convert(element));
    if (ids == null || ids.isEmpty()) {
        throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
    }
    List<SimpleTimer.Context> contexts = ids.stream()
            .map(metricID -> {
                SimpleTimer metric = registry.getSimpleTimers().get(metricID);
                if (metric == null) {
                    throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.SIMPLE_TIMER, metricID);
                }
                return metric;
            })
            .map(SimpleTimer::time)
            .collect(Collectors.toList());
    try {
        return invocationContext.proceed();
    } finally {
        for (SimpleTimer.Context timeContext : contexts) {
            timeContext.stop();
        }
    }
}
 
Example #16
Source File: CountedInterceptor.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private <E extends Member & AnnotatedElement> Object countedCallable(InvocationContext context, E element)
        throws Exception {
    Set<MetricID> ids = ((MetricsRegistryImpl) registry).getMemberToMetricMappings()
            .getCounters(new CDIMemberInfoAdapter<>().convert(element));
    if (ids == null || ids.isEmpty()) {
        throw SmallRyeMetricsMessages.msg.noMetricMappedForMember(element);
    }
    ids.stream()
            .map(metricID -> {
                Counter metric = registry.getCounters().get(metricID);
                if (metric == null) {
                    throw SmallRyeMetricsMessages.msg.noMetricFoundInRegistry(MetricType.COUNTER, metricID);
                }
                return metric;
            })
            .forEach(Counter::inc);
    return context.proceed();
}
 
Example #17
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
public static void registerMetrics(Schema schema, MetricRegistry metricRegistry) {
    findAllOperations(schema)
            .forEach(operation -> {
                final String description;
                final String name = MetricNaming.fromOperation(operation);
                if (operation.getOperationType() == OperationType.Mutation) {
                    description = "Call statistics for the mutation '" + operation.getName() + "'";
                } else if (operation.getOperationType() == OperationType.Query) {
                    description = "Call statistics for the query '" + operation.getName() + "'";
                } else {
                    description = "Call statistics for the query '" + operation.getName()
                            + "' on type '" + operation.getContainingType().getName() + "'";
                }

                Metadata metadata = Metadata.builder()
                        .withName(name)
                        .withType(MetricType.SIMPLE_TIMER)
                        .withDescription(description)
                        .build();
                metricRegistry.simpleTimer(metadata);
            });
}
 
Example #18
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 #19
Source File: SmallRyeMetricsRecorder.java    From quarkus with 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()));
    }
}
 
Example #20
Source File: Summary.java    From trader with Apache License 2.0 5 votes vote down vote up
void setPortfolioMetric(String owner, double total) {
	totals.put(owner, total);
	if (gauges.get(owner)==null) try { //gauge not yet registered for this portfolio
		org.eclipse.microprofile.metrics.Gauge<Double> gauge = () -> { return totals.get(owner); };

		Metadata metadata = Metadata.builder().withName("portfolio_value").withType(MetricType.GAUGE).withUnit(DOLLARS).build();

		metricRegistry.register(metadata, gauge, new Tag("owner", owner)); //registry injected via CDI

		gauges.put(owner, gauge);
	} catch (Throwable t) {
		logger.warning(t.getMessage());
	}
}
 
Example #21
Source File: OpenMetricsExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private void createSimpleValueLine(StringBuilder sb, MetricRegistry.Type scope, String key, Metadata md, Metric metric,
        String suffix, Map<String, String> tags) {

    // value line
    fillBaseName(sb, scope, key, suffix, md);
    // append the base unit only in case that the key wasn't overridden
    if (getOpenMetricsKeyOverride(md) == null) {
        String unit = OpenMetricsUnit.getBaseUnitAsOpenMetricsString(md.unit());
        if (!unit.equals(NONE)) {
            sb.append(USCORE).append(unit);
        }
    }

    addTags(sb, tags, scope, md);

    double valIn;
    if (md.getTypeRaw().equals(MetricType.GAUGE)) {
        Number value1 = (Number) ((Gauge) metric).getValue();
        if (value1 != null) {
            valIn = value1.doubleValue();
        } else {
            valIn = Double.NaN;
        }
    } else {
        valIn = (double) ((Counter) metric).getCount();
    }

    Double value = OpenMetricsUnit.scaleToBase(md.unit().orElse(NONE), valIn);
    sb.append(SPACE).append(value).append(LF);

}
 
Example #22
Source File: RegistrationCornerCasesTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void lambdaExpression() {
    registry.register("test", (Gauge<Long>) () -> 42L);

    Assert.assertEquals(MetricType.GAUGE, registry.getMetadata("test").getTypeRaw());
    Assert.assertEquals(42L, registry.getGauge(new MetricID("test")).getValue());
}
 
Example #23
Source File: KeycloakMetrics.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a counter based on a event name
 */
private static Metadata createCounter(final String name, boolean isAdmin) {

    String description = isAdmin ? "Generic KeyCloak Admin event" : "Generic KeyCloak User event";

    return Metadata.builder()
            .withName(name)
            .withDescription(description)
            .withType(MetricType.COUNTER).build();
}
 
Example #24
Source File: RegistrationCornerCasesTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void ambiguousClassButTypeIsProvidedDuringRegistration() {
    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());

    Assert.assertEquals(MetricType.COUNTER, registry.getMetadata("test").getTypeRaw());
    Assert.assertEquals(666L, registry.getCounter(new MetricID("test")).getCount());
}
 
Example #25
Source File: RegistrationCornerCasesTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void specialClass() {
    registry.register("test", new LambdaGauge(() -> 42L));

    Assert.assertEquals(MetricType.GAUGE, registry.getMetadata("test").getTypeRaw());
    Assert.assertEquals(42L, registry.getGauge(new MetricID("test")).getValue());
}
 
Example #26
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private Metadata sanitizeMetadata(Metadata metadata, MetricType metricType) {
    // if the metadata does not specify a type, we add it here
    // if the metadata specifies a type, we check that it's the correct one
    // (for example, someone might have called registry.counter(metadata) where metadata.type="gauge")
    if (metadata.getTypeRaw() == null || metadata.getTypeRaw() == MetricType.INVALID) {
        return Metadata.builder(metadata).withType(metricType).build();
    } else {
        if (metadata.getTypeRaw() != metricType) {
            throw SmallRyeMetricsMessages.msg.typeMismatch(metricType, metadata.getTypeRaw());
        } else {
            return metadata;
        }
    }
}
 
Example #27
Source File: RegistrationCornerCasesTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void lambdaCastToInterfaceThatExtendsGauge() {
    registry.register("test", (MySpecialThing) (() -> 42L));

    Assert.assertEquals(MetricType.GAUGE, registry.getMetadata("test").getTypeRaw());
    Assert.assertEquals(42L, registry.getGauge(new MetricID("test")).getValue());
}
 
Example #28
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 #29
Source File: MetricBuildItem.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * Create a metric build item from the specified metadata and tags.
 * Such metric will be picked up by the Metrics extension and registered in the VENDOR registry.
 * This constructor is applicable to all metric types except gauges.
 *
 * @param metadata The metadata that should be applied to the registered metric
 * @param enabled Whether this metric is enabled
 * @param tags The tags that will be applied to this metric
 * @param configRootName the name of the root configuration of the extension as defined by the <code>@ConfigRoot</code>
 *        annotation.
 */
public MetricBuildItem(Metadata metadata, boolean enabled, String configRootName, Tag... tags) {
    if (metadata.getTypeRaw() == MetricType.GAUGE) {
        throw new IllegalArgumentException("Gauges require a non-null implementation object");
    }
    this.metadata = metadata;
    this.tags = tags;
    this.implementor = null;
    this.enabled = enabled;
    this.configRootName = configRootName;
    this.registryType = MetricRegistry.Type.VENDOR;
}
 
Example #30
Source File: GaugeRegistrationInterceptor.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@AroundConstruct
Object metrics(InvocationContext context) throws Exception {
    Class<?> type = context.getConstructor().getDeclaringClass();

    Object target = context.proceed();

    BeanInfoAdapter<Class<?>> beanInfoAdapter = new CDIBeanInfoAdapter();
    MemberInfoAdapter<Member> memberInfoAdapter = new CDIMemberInfoAdapter();
    // Registers the gauges over the bean type hierarchy after the target is constructed as it is required for the gauge invocations
    do {
        // TODO: discover annotations declared on implemented interfaces
        for (Method method : type.getDeclaredMethods()) {
            MetricResolver.Of<Gauge> gauge = resolver.gauge(beanInfoAdapter.convert(type),
                    memberInfoAdapter.convert(method));
            if (gauge.isPresent()) {
                AnnotationInfo g = gauge.metricAnnotation();
                Metadata metadata = MetricsMetadata.getMetadata(g, gauge.metricName(), g.unit(), g.description(),
                        g.displayName(), MetricType.GAUGE);
                registry.register(metadata, new ForwardingGauge(method, context.getTarget()),
                        TagsUtils.parseTagsAsArray(g.tags()));
            }
        }
        type = type.getSuperclass();
    } while (!Object.class.equals(type));

    return target;
}