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

The following examples show how to use org.eclipse.microprofile.metrics.MetricType. 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
Source Project: smallrye-graphql   Source File: Bootstrap.java    License: 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 2
Source Project: microprofile-metrics   Source File: MetricRegistryTest.java    License: 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 3
/**
 * 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 4
Source Project: smallrye-metrics   Source File: JsonExporterTest.java    License: 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 5
Source Project: smallrye-metrics   Source File: MemberToMetricMappings.java    License: 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 6
/**
 * 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 7
/**
 * 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 8
/**
 * 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 9
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 10
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 11
/**
 * 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 12
Source Project: smallrye-metrics   Source File: MetricsRegistryImpl.java    License: 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 13
Source Project: smallrye-metrics   Source File: MetricsRegistryImpl.java    License: 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 14
/**
 * 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 15
Source Project: smallrye-metrics   Source File: MeteredInterceptor.java    License: 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 16
Source Project: smallrye-metrics   Source File: SimplyTimedInterceptor.java    License: 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 17
Source Project: smallrye-metrics   Source File: CountedInterceptor.java    License: 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 18
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: 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 Project: quarkus   Source File: HibernateOrmProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private MetricBuildItem createMetricBuildItem(String metricName, String description, String metric,
        boolean metricsEnabled) {
    return new MetricBuildItem(Metadata.builder()
            .withName(metricName)
            .withDescription(description)
            .withType(MetricType.COUNTER)
            .build(),
            new HibernateCounter("default", metric),
            metricsEnabled,
            "hibernate-orm");
}
 
Example 20
/**
 * 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 21
private Counter counterOf(String name) {
    MetricID metricID = new MetricID(name);
    Counter counter = registry.getCounters().get(metricID);
    if (counter == null) {
        synchronized (operation) {
            counter = registry.getCounters().get(metricID);
            if (counter == null) {
                counter = registry.counter(metadataOf(name, MetricType.COUNTER));
            }
        }
    }
    return counter;
}
 
Example 22
private Histogram histogramOf(String name) {
    MetricID metricID = new MetricID(name);
    Histogram histogram = registry.getHistograms().get(metricID);
    if (histogram == null) {
        synchronized (operation) {
            histogram = registry.getHistograms().get(metricID);
            if (histogram == null) {
                histogram = registry.histogram(metadataOf(name, MetricType.HISTOGRAM));
            }
        }
    }
    return histogram;
}
 
Example 23
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()));
    }
}
 
Example 24
Source Project: smallrye-metrics   Source File: OpenMetricsExporterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void exportSimpleTimers() {
    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    Metadata metadata = Metadata
            .builder()
            .withType(MetricType.SIMPLE_TIMER)
            .withName("mysimpletimer")
            .withDescription("awesome")
            .build();
    Tag blueTag = new Tag("color", "blue");
    SimpleTimer blueTimer = registry.simpleTimer(metadata, blueTag);
    Tag greenTag = new Tag("color", "green");
    SimpleTimer greenTimer = registry.simpleTimer(metadata, greenTag);

    blueTimer.update(Duration.ofSeconds(3));
    blueTimer.update(Duration.ofSeconds(4));
    greenTimer.update(Duration.ofSeconds(5));
    greenTimer.update(Duration.ofSeconds(6));

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

    assertHasTypeLineExactlyOnce(result, "application_mysimpletimer_total", "counter");
    assertHasTypeLineExactlyOnce(result, "application_mysimpletimer_elapsedTime_seconds", "gauge");
    assertHasHelpLineExactlyOnce(result, "application_mysimpletimer_total", "awesome");

    assertHasValueLineExactlyOnce(result, "application_mysimpletimer_total", "2.0", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mysimpletimer_total", "2.0", greenTag);

    assertHasValueLineExactlyOnce(result, "application_mysimpletimer_elapsedTime_seconds", "7.0", blueTag);
    assertHasValueLineExactlyOnce(result, "application_mysimpletimer_elapsedTime_seconds", "11.0", greenTag);
}
 
Example 25
Source Project: smallrye-metrics   Source File: ExtendedMetadata.java    License: Apache License 2.0 5 votes vote down vote up
public ExtendedMetadata(String name, String displayName, String description, MetricType typeRaw, String unit, String mbean,
        boolean multi, Optional<Boolean> prependsScopeToOpenMetricsName, boolean skipsScopeInOpenMetricsExportCompletely,
        String openMetricsKeyOverride) {
    super(name, displayName, description, typeRaw, unit);
    this.mbean = mbean;
    this.multi = multi;
    this.prependsScopeToOpenMetricsName = prependsScopeToOpenMetricsName;
    this.skipsScopeInOpenMetricsExportCompletely = skipsScopeInOpenMetricsExportCompletely;
    this.openMetricsKeyOverride = Optional.ofNullable(openMetricsKeyOverride);
}
 
Example 26
Source Project: quarkus   Source File: JaegerProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void produceMetrics(BuildProducer<MetricBuildItem> producer) {
    producer.produce(
            metric("jaeger_tracer_baggage_restrictions_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(
            metric("jaeger_tracer_baggage_restrictions_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_baggage_truncations", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_baggage_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_baggage_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_finished_spans", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "dropped")));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_reporter_spans", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_queries", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_sampler_queries", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_updates", MetricType.COUNTER, null, new Tag("result", "ok")));
    producer.produce(metric("jaeger_tracer_sampler_updates", MetricType.COUNTER, null, new Tag("result", "err")));
    producer.produce(metric("jaeger_tracer_span_context_decoding_errors", MetricType.COUNTER, null));
    producer.produce(metric("jaeger_tracer_started_spans", MetricType.COUNTER, null, new Tag("sampled", "n")));
    producer.produce(metric("jaeger_tracer_started_spans", MetricType.COUNTER, null, new Tag("sampled", "y")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "y"), new Tag("state", "joined")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "y"), new Tag("state", "started")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "n"), new Tag("state", "joined")));
    producer.produce(metric("jaeger_tracer_traces", MetricType.COUNTER, null,
            new Tag("sampled", "n"), new Tag("state", "started")));
    producer.produce(
            metric("jaeger_tracer_reporter_queue_length", MetricType.GAUGE, new QuarkusJaegerMetricsFactory.JaegerGauge()));
}
 
Example 27
Source Project: quarkus   Source File: QuarkusJaegerMetricsFactory.java    License: Apache License 2.0 5 votes vote down vote up
static Metadata meta(String name, MetricType type) {
    return Metadata.builder()
            .withName(name)
            .withDisplayName(name)
            .withType(type)
            .withUnit("none")
            .withDescription(name)
            .reusable()
            .build();
}
 
Example 28
Source Project: trader   Source File: Summary.java    License: 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 29
Source Project: smallrye-metrics   Source File: OpenMetricsExporter.java    License: 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 30
@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());
}