org.eclipse.microprofile.metrics.Metric Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.Metric. 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: 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 #2
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public void registerMetricFromProducer(String beanId, MetricType metricType,
        String metricName, String[] tags, String description,
        String displayName, String unit) {
    ArcContainer container = Arc.container();
    InjectableBean<Object> injectableBean = container.bean(beanId);
    BeanManager beanManager = container.beanManager();
    Metric reference = (Metric) beanManager.getReference(injectableBean, Metric.class,
            beanManager.createCreationalContext(injectableBean));
    MetricRegistry registry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);
    Metadata metadata = Metadata.builder()
            .withType(metricType)
            .withName(metricName)
            .withDescription(description)
            .withDisplayName(displayName)
            .withUnit(unit)
            .notReusable()
            .build();
    registry.register(metadata, reference, TagsUtils.parseTagsAsArray(tags));
}
 
Example #3
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder exportOneMetric(MetricRegistry.Type scope, MetricID metricID) {
    MetricRegistry registry = MetricRegistries.get(scope);
    Map<MetricID, Metric> metricMap = registry.getMetrics();
    Map<String, Metadata> metadataMap = registry.getMetadata();

    Metric m = metricMap.get(metricID);

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

    JsonObjectBuilder root = JsonProviderHolder.get().createObjectBuilder();
    exportMetricsForMap(outMap, metadataMap)
            .forEach(root::add);
    return stringify(root.build());
}
 
Example #4
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder exportMetricsByName(MetricRegistry.Type scope, String name) {
    MetricRegistry registry = MetricRegistries.get(scope);
    Map<MetricID, Metric> metricMap = registry.getMetrics()
            .entrySet()
            .stream()
            .filter(e -> e.getKey().getName().equals(name))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue));
    Map<String, Metadata> metadataMap = registry.getMetadata();

    JsonObjectBuilder root = JsonProviderHolder.get().createObjectBuilder();
    exportMetricsForMap(metricMap, metadataMap)
            .forEach(root::add);
    return stringify(root.build());
}
 
Example #5
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private Map<String, JsonValue> exportMetricsForMap(Map<MetricID, Metric> metricMap, Map<String, Metadata> metadataMap) {
    Map<String, JsonValue> result = new HashMap<>();

    // split into groups by metric name
    Map<String, Map<MetricID, Metric>> metricsGroupedByName = metricMap.entrySet().stream()
            .collect(Collectors.groupingBy(
                    entry -> entry.getKey().getName(),
                    Collectors.mapping(e -> e, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));
    // and then for each group, perform the export
    metricsGroupedByName.entrySet().stream()
            .map(entry -> exportMetricsByName(entry.getValue(), metadataMap.get(entry.getKey())))
            .forEach(map -> {
                map.forEach(result::put);
            });
    return result;
}
 
Example #6
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized <T extends Metric> T register(String name, T metric) {

    final MetricID metricID = new MetricID(name);
    if (metricMap.keySet().contains(metricID)) {
        throw SmallRyeMetricsMessages.msg.metricWithNameAlreadyExists(name);
    }

    MetricType type = inferMetricType(metric.getClass());
    if (type == null || type.equals(MetricType.INVALID)) {
        throw SmallRyeMetricsMessages.msg.unableToInferMetricType();
    }

    Metadata m = Metadata.builder().withName(name).withType(type).build();
    metricMap.put(metricID, metric);
    metadataMap.put(name, m);
    return metric;
}
 
Example #7
Source File: OpenMetricsExporter.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public StringBuilder exportOneMetric(MetricRegistry.Type scope, MetricID metricID) {
    alreadyExportedNames.set(new HashSet<>());
    MetricRegistry registry = MetricRegistries.get(scope);
    Map<MetricID, Metric> metricMap = registry.getMetrics();

    Metric m = metricMap.get(metricID);

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

    StringBuilder sb = new StringBuilder();
    exposeEntries(scope, sb, registry, outMap);
    alreadyExportedNames.set(null);
    return sb;
}
 
Example #8
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 #9
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private JsonObject exportOneRegistry(MetricRegistry registry) {
    Map<MetricID, Metric> metricMap = registry.getMetrics();
    Map<String, Metadata> metadataMap = registry.getMetadata();

    JsonObjectBuilder root = JsonProviderHolder.get().createObjectBuilder();
    exportMetricsForMap(metricMap, metadataMap)
            .forEach(root::add);
    return root.build();
}
 
Example #10
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private JsonValue exportSimpleMetric(MetricID metricID, Metric metric) {
    Number val = getValueFromMetric(metric, metricID.getName());
    if (val instanceof Double) {
        return JsonProviderHolder.get().createValue((Double) val);
    } else if (val instanceof Float) {
        return JsonProviderHolder.get().createValue((Float) val);
    } else if (val instanceof Integer) {
        return JsonProviderHolder.get().createValue((Integer) val);
    } else if (val instanceof Long) {
        return JsonProviderHolder.get().createValue((Long) val);
    } else {
        throw new IllegalStateException();
    }
}
 
Example #11
Source File: JsonExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private Number getValueFromMetric(Metric theMetric, String name) {
    if (theMetric instanceof Gauge) {
        Number value = (Number) ((Gauge) theMetric).getValue();
        if (value != null) {
            return value;
        } else {
            return 0;
        }
    } else if (theMetric instanceof Counter) {
        return ((Counter) theMetric).getCount();
    } else {
        return null;
    }
}
 
Example #12
Source File: OpenMetricsExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public StringBuilder exportMetricsByName(MetricRegistry.Type scope, String name) {
    alreadyExportedNames.set(new HashSet<>());
    MetricRegistry registry = MetricRegistries.get(scope);
    Map<MetricID, Metric> metricsToExport = registry.getMetrics()
            .entrySet()
            .stream()
            .filter(entry -> entry.getKey().getName().equals(name))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    StringBuilder sb = new StringBuilder();
    exposeEntries(scope, sb, registry, metricsToExport);
    alreadyExportedNames.set(null);
    return sb;
}
 
Example #13
Source File: MetricRegistryInjectionTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjection() {
    hello.hello();
    assertTrue(summary.getBaseMetrics().getMetrics().containsKey(new MetricID("memory.usedHeap")));
    assertTrue(summary.getVendorMetrics().getMetrics().containsKey(new MetricID("loadedModules")));
    Metric helloCountMetric = summary.getAppMetrics().getMetrics().get(new MetricID("hello-count"));
    assertNotNull(helloCountMetric);
    assertTrue(helloCountMetric instanceof Counting);
    Counting helloCount = (Counting) helloCountMetric;
    assertEquals(1, helloCount.getCount());
}
 
Example #14
Source File: MongoMetricsTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Long getGaugeValueOrNull(String metricName, Tag[] tags) {
    MetricID metricID = new MetricID(metricName, tags);
    Metric metric = registry.getMetrics().get(metricID);

    if (metric == null) {
        return null;
    }
    return ((ConnectionPoolGauge) metric).getValue();
}
 
Example #15
Source File: MongoMetricsConnectionPoolListener.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionCheckedOut(ConnectionCheckedOutEvent event) {
    MetricID metricID = createMetricID(CHECKED_OUT_COUNT_NAME, event.getConnectionId().getServerId());

    Metric metric = getMetricRegistry().getMetrics().get(metricID);

    if (metric != null) {
        ((ConnectionPoolGauge) metric).increment();
    }
}
 
Example #16
Source File: MongoMetricsConnectionPoolListener.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionCheckedIn(ConnectionCheckedInEvent event) {
    MetricID metricID = createMetricID(CHECKED_OUT_COUNT_NAME, event.getConnectionId().getServerId());

    Metric metric = getMetricRegistry().getMetrics().get(metricID);

    if (metric != null) {
        ((ConnectionPoolGauge) metric).decrement();
    }
}
 
Example #17
Source File: MongoMetricsConnectionPoolListener.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionAdded(ConnectionAddedEvent event) {

    MetricID metricID = createMetricID(SIZE_NAME, event.getConnectionId().getServerId());

    Metric metric = getMetricRegistry().getMetrics().get(metricID);

    if (metric != null) {
        ((ConnectionPoolGauge) metric).increment();
    }
}
 
Example #18
Source File: MongoMetricsConnectionPoolListener.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void connectionRemoved(ConnectionRemovedEvent event) {

    MetricID metricID = createMetricID(SIZE_NAME, event.getConnectionId().getServerId());

    Metric metric = getMetricRegistry().getMetrics().get(metricID);

    if (metric != null) {
        ((ConnectionPoolGauge) metric).decrement();
    }
}
 
Example #19
Source File: MetricGetter.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
private <T> Optional<T> getMetric(MetricID id, Class<T> metricType) {
    Metric m = registry.getMetrics().get(id);
    if (m != null) {
        assertThat("Metric " + id, m, instanceOf(metricType));
        return Optional.of(metricType.cast(m));
    }
    else {
        return Optional.empty();
    }
}
 
Example #20
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public SortedMap<MetricID, Metric> getMetrics(MetricFilter filter) {
    SortedMap<MetricID, Metric> out = new TreeMap<>();
    for (Map.Entry<MetricID, Metric> entry : metricMap.entrySet()) {
        if (filter.matches(entry.getKey(), entry.getValue())) {
            out.put(entry.getKey(), entry.getValue());
        }
    }
    return out;
}
 
Example #21
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Metric> T getMetric(MetricID metricID, Class<T> asType) {
    try {
        return asType.cast(getMetric(metricID));
    } catch (ClassCastException e) {
        throw new IllegalArgumentException(metricID + " was not of expected type " + asType, e);
    }
}
 
Example #22
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public void removeMatching(MetricFilter metricFilter) {
    Iterator<Map.Entry<MetricID, Metric>> iterator = metricMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<MetricID, Metric> entry = iterator.next();
        if (metricFilter.matches(entry.getKey(), entry.getValue())) {
            remove(entry.getKey());
        }
    }
}
 
Example #23
Source File: MetricsRegistryImpl.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private <T extends Metric> SortedMap<MetricID, T> getMetrics(MetricType type, MetricFilter filter) {
    SortedMap<MetricID, T> out = new TreeMap<>();

    for (Map.Entry<MetricID, Metric> entry : metricMap.entrySet()) {
        if (isSameType(entry.getValue(), type)) {
            if (filter.matches(entry.getKey(), entry.getValue())) {
                out.put(entry.getKey(), (T) entry.getValue());
            }
        }
    }
    return out;
}
 
Example #24
Source File: MetricRegistryInjectionTest.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjection() {
    hello.hello();
    assertNotNull(summary.getBaseMetrics().getMetrics().containsKey("memory.usedHeap"));
    assertNotNull(summary.getVendorMetrics().getMetrics().containsKey("loadedModules"));
    Metric helloCountMetric = summary.getAppMetrics().getMetrics().get(new MetricID("hello-count"));
    assertNotNull(helloCountMetric);
    assertTrue(helloCountMetric instanceof Counting);
    Counting helloCount = (Counting) helloCountMetric;
    assertEquals(1, helloCount.getCount());
}
 
Example #25
Source File: JmxRegistrar.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
void register(MetricRegistry registry, ExtendedMetadata config, List<Tag> tags) {
    Metric metric = null;
    switch (config.getTypeRaw()) {
        case COUNTER:
            metric = new MCounterImpl(JmxWorker.instance(), config.getMbean());
            break;
        case GAUGE:
            metric = new MGaugeImpl(JmxWorker.instance(), config.getMbean());
            break;
    }

    if (metric != null) {
        registry.register(config, metric, tags.toArray(new Tag[] {}));
    }
}
 
Example #26
Source File: MetricCdiInjectionExtension.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
private void findMetricProducerMethods(@Observes ProcessProducerMethod<? extends Metric, ?> ppm) {
    if (!ppm.getBean().getBeanClass().equals(MetricProducer.class)) {
        SmallRyeMetricsLogging.log.producerMethodDiscovered(ppm.getAnnotatedProducerMethod());
        metricsFromProducers.put(ppm.getBean(), ppm.getAnnotatedProducerMethod());
    }
}
 
Example #27
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #28
Source File: TestMetricsServiceImpl.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Metric> T register(Metadata metadata, T metric) throws IllegalArgumentException {
    throw new UnsupportedOperationException("unimplemented");
}
 
Example #29
Source File: MeteredClassBeanTest.java    From microprofile-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(MetricID metricID, Metric metric) {
    return METHOD_METER_NAMES.contains(metricID.getName());
}
 
Example #30
Source File: CountedClassBeanTest.java    From microprofile-metrics with Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(MetricID metricID, Metric metric) {
    return METHOD_COUNTER_NAMES.contains(metricID.getName());
}