Java Code Examples for org.eclipse.microprofile.metrics.MetricRegistry#register()

The following examples show how to use org.eclipse.microprofile.metrics.MetricRegistry#register() . 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 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 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: 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 4
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentTimerImplementations() {

    JsonExporter exporter = new JsonExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    // the export should behave identical for any class derived from Timer
    Timer[] timers = { new TimerImpl(), new SomeTimer() };
    int idx = 0;
    for (Timer t : timers) {
        String name = "json_timer_" + idx++;
        applicationRegistry.register(name, t);
        StringBuilder out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name));
        assertNotNull(out);
        List<String> lines = Arrays.asList(out.toString().split(LINE_SEPARATOR));
        assertEquals(1, lines.stream().filter(line -> line.contains("\"" + name + "\"")).count());
        assertEquals(1, lines.stream().filter(line -> line.contains("\"count\": 0")).count());
    }
}
 
Example 5
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentHistogramImplementations() {

    JsonExporter exporter = new JsonExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    // the export should behave identical for any class derived from Histogram
    Histogram[] histograms = { new HistogramImpl(new ExponentiallyDecayingReservoir()), new SomeHistogram() };
    int idx = 0;
    for (Histogram h : histograms) {
        String name = "histo_" + idx++;
        applicationRegistry.register(name, h);
        StringBuilder out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name));
        assertNotNull(out);
        System.out.println(out.toString());
        List<String> lines = Arrays.asList(out.toString().split(LINE_SEPARATOR));
        assertEquals(1, lines.stream().filter(line -> line.contains("\"" + name + "\"")).count());
        assertEquals(1, lines.stream().filter(line -> line.contains("\"count\": 0")).count());
    }
}
 
Example 6
Source File: JsonExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentMeterImplementations() {

    JsonExporter exporter = new JsonExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    // the export should behave identical for any class derived from Meter
    Meter[] meters = { new MeterImpl(), new SomeMeter() };
    int idx = 0;
    for (Meter m : meters) {
        String name = "meter_" + idx++;
        applicationRegistry.register(name, m);
        StringBuilder out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name));
        assertNotNull(out);
        List<String> lines = Arrays.asList(out.toString().split(LINE_SEPARATOR));
        assertEquals(1, lines.stream().filter(line -> line.contains("\"" + name + "\"")).count());
        assertEquals(1, lines.stream().filter(line -> line.contains("\"count\": 0")).count());
    }
}
 
Example 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: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentHistogramImplementations() {

    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    // the export should behave identical for any class derived from Histogram
    Histogram[] histograms = { new HistogramImpl(new ExponentiallyDecayingReservoir()), new SomeHistogram() };
    int idx = 0;
    for (Histogram h : histograms) {
        String name = "histo_" + idx++;
        applicationRegistry.register(name, h);
        String out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name)).toString();
        String expectedLine = "application_" + name + "_mean 0.0";
        assertThat(out, containsString(expectedLine));
    }
}
 
Example 9
Source File: OpenMetricsExporterTest.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testExportOfDifferentMeterImplementations() {

    OpenMetricsExporter exporter = new OpenMetricsExporter();
    MetricRegistry applicationRegistry = MetricRegistries.get(MetricRegistry.Type.APPLICATION);

    // the export should behave identical for any class derived from Meter
    Meter[] meters = { new MeterImpl(), new SomeMeter() };
    int idx = 0;
    for (Meter m : meters) {
        String name = "meter_" + idx++;
        applicationRegistry.register(name, m);
        String out = exporter.exportOneMetric(MetricRegistry.Type.APPLICATION, new MetricID(name)).toString();
        String expectedLine = "application_" + name + "_total 0.0";
        assertThat(out, containsString(expectedLine));
    }
}
 
Example 10
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 11
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 12
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 13
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void micrometerJvmThreadMetrics(MetricRegistry registry) {
    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("jvm.threads.peak")
                    .withType(MetricType.GAUGE)
                    .withUnit("threads")
                    .withDescription("The peak live thread count since the Java virtual machine started or peak was reset")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return threadBean.getPeakThreadCount();
                }
            });
    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("jvm.threads.daemon")
                    .withType(MetricType.GAUGE)
                    .withUnit("threads")
                    .withDescription("The current number of live daemon threads")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return threadBean.getDaemonThreadCount();
                }
            });
    registry.register(
            new ExtendedMetadataBuilder()
                    .withName("jvm.threads.live")
                    .withType(MetricType.GAUGE)
                    .withUnit("threads")
                    .withDescription("The current number of live threads including both daemon and non-daemon threads")
                    .skipsScopeInOpenMetricsExportCompletely(true)
                    .build(),
            new Gauge() {
                @Override
                public Number getValue() {
                    return threadBean.getThreadCount();
                }
            });

    if (!ImageInfo.inImageCode()) {
        ExtendedMetadata threadStatesMetadata = new ExtendedMetadataBuilder()
                .withName("jvm.threads.states")
                .withType(MetricType.GAUGE)
                .withUnit("threads")
                .withDescription("The current number of threads having a particular state")
                .skipsScopeInOpenMetricsExportCompletely(true)
                .build();
        for (Thread.State state : Thread.State.values()) {
            registry.register(threadStatesMetadata,
                    new Gauge() {
                        @Override
                        public Number getValue() {
                            return getThreadStateCount(threadBean, state);
                        }
                    },
                    new Tag("state", state.name().toLowerCase().replace("_", "-")));
        }
    }
}
 
Example 14
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void baseMemoryMetrics(MetricRegistry registry) {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    Metadata meta = Metadata.builder()
            .withName(MEMORY_COMMITTED_HEAP)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.BYTES)
            .withDisplayName("Committed Heap Memory")
            .withDescription(
                    "Displays the amount of memory in bytes that is committed for the Java virtual machine to use. " +
                            "This amount of memory is guaranteed for the Java virtual machine to use.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return memoryMXBean.getHeapMemoryUsage().getCommitted();
        }
    });

    meta = Metadata.builder()
            .withName(MEMORY_MAX_HEAP)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.BYTES)
            .withDisplayName("Max Heap Memory")
            .withDescription("Displays the maximum amount of heap memory in bytes that can be used for memory management. "
                    +
                    "This attribute displays -1 if the maximum heap memory size is undefined. This amount of memory is not "
                    +
                    "guaranteed to be available for memory management if it is greater than the amount of committed memory. "
                    +
                    "The Java virtual machine may fail to allocate memory even if the amount of used memory does " +
                    "not exceed this maximum size.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return memoryMXBean.getHeapMemoryUsage().getMax();
        }
    });

    meta = Metadata.builder()
            .withName(MEMORY_USED_HEAP)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.BYTES)
            .withDisplayName("Used Heap Memory")
            .withDescription("Displays the amount of used heap memory in bytes.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return memoryMXBean.getHeapMemoryUsage().getUsed();
        }
    });
}
 
Example 15
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void memoryPoolMetrics(MetricRegistry registry) {
    // MemoryPoolMXBean doesn't work in native mode
    if (!ImageInfo.inImageCode()) {
        List<MemoryPoolMXBean> mps = ManagementFactory.getMemoryPoolMXBeans();
        Metadata usageMetadata = Metadata.builder()
                .withName("memoryPool.usage")
                .withType(MetricType.GAUGE)
                .withDisplayName("Current usage of the memory pool denoted by the 'name' tag")
                .withDescription("Current usage of the memory pool denoted by the 'name' tag")
                .withUnit(MetricUnits.BYTES)
                .build();
        Metadata maxMetadata = Metadata.builder()
                .withName("memoryPool.usage.max")
                .withType(MetricType.GAUGE)
                .withDisplayName("Peak usage of the memory pool denoted by the 'name' tag")
                .withDescription("Peak usage of the memory pool denoted by the 'name' tag")
                .withUnit(MetricUnits.BYTES)
                .build();
        for (MemoryPoolMXBean mp : mps) {
            if (mp.getCollectionUsage() != null && mp.getPeakUsage() != null) {
                // this will be the case for the heap memory pools
                registry.register(usageMetadata, new Gauge() {
                    @Override
                    public Number getValue() {
                        return mp.getCollectionUsage().getUsed();
                    }
                },
                        new Tag("name", mp.getName()));

                registry.register(maxMetadata, new Gauge() {
                    @Override
                    public Number getValue() {
                        return mp.getPeakUsage().getUsed();
                    }
                },
                        new Tag("name", mp.getName()));
            } else if (mp.getUsage() != null && mp.getPeakUsage() != null) {
                // this will be the case for the non-heap memory pools
                registry.register(usageMetadata, new Gauge() {
                    @Override
                    public Number getValue() {
                        return mp.getUsage().getUsed();
                    }
                },
                        new Tag("name", mp.getName()));

                registry.register(maxMetadata, new Gauge() {
                    @Override
                    public Number getValue() {
                        return mp.getPeakUsage().getUsed();
                    }
                },
                        new Tag("name", mp.getName()));
            }
        }
    }
}
 
Example 16
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void vendorSpecificMemoryMetrics(MetricRegistry registry) {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

    Metadata meta = Metadata.builder()
            .withName(MEMORY_COMMITTED_NON_HEAP)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.BYTES)
            .withDisplayName("Committed Non Heap Memory")
            .withDescription(
                    "Displays the amount of non heap memory in bytes that is committed for the Java virtual machine to use.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return memoryMXBean.getNonHeapMemoryUsage().getCommitted();
        }
    });

    meta = Metadata.builder()
            .withName(MEMORY_MAX_NON_HEAP)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.BYTES)
            .withDisplayName("Max Non Heap Memory")
            .withDescription("Displays the maximum amount of used non-heap memory in bytes.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return memoryMXBean.getNonHeapMemoryUsage().getMax();
        }
    });

    meta = Metadata.builder()
            .withName(MEMORY_USED_NON_HEAP)
            .withType(MetricType.GAUGE)
            .withUnit(MetricUnits.BYTES)
            .withDisplayName("Used Non Heap Memory")
            .withDescription("Displays the amount of used non-heap memory in bytes.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return memoryMXBean.getNonHeapMemoryUsage().getUsed();
        }
    });
}
 
Example 17
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public void registerMetric(MetricRegistry.Type scope,
        MetadataHolder metadataHolder,
        TagHolder[] tagHolders,
        Object implementor) {
    Metadata metadata = metadataHolder.toMetadata();
    Tag[] tags = Arrays.stream(tagHolders).map(TagHolder::toTag).toArray(Tag[]::new);
    MetricRegistry registry = MetricRegistries.get(scope);

    switch (metadata.getTypeRaw()) {
        case GAUGE:
            registry.register(metadata, (Gauge) implementor, tags);
            break;
        case TIMER:
            if (implementor == null) {
                registry.timer(metadata, tags);
            } else {
                registry.register(metadata, (Timer) implementor);
            }
            break;
        case COUNTER:
            if (implementor == null) {
                registry.counter(metadata, tags);
            } else {
                registry.register(metadata, (Counter) implementor, tags);
            }
            break;
        case HISTOGRAM:
            if (implementor == null) {
                registry.histogram(metadata, tags);
            } else {
                registry.register(metadata, (Histogram) implementor, tags);
            }
            break;
        case CONCURRENT_GAUGE:
            if (implementor == null) {
                registry.concurrentGauge(metadata, tags);
            } else {
                registry.register(metadata, (ConcurrentGauge) implementor, tags);
            }
            break;
        case METERED:
            if (implementor == null) {
                registry.meter(metadata, tags);
            } else {
                registry.register(metadata, (Metered) implementor, tags);
            }
            break;
        case INVALID:
            break;
        default:
            break;
    }
}
 
Example 18
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void classLoadingMetrics(MetricRegistry registry) {
    ClassLoadingMXBean classLoadingMXBean = ManagementFactory.getClassLoadingMXBean();

    Metadata meta = Metadata.builder()
            .withName(TOTAL_LOADED_CLASS_COUNT)
            .withType(MetricType.COUNTER)
            .withDisplayName("Total Loaded Class Count")
            .withDescription(
                    "Displays the total number of classes that have been loaded since the Java virtual machine has started execution.")
            .build();
    registry.register(meta, new GetCountOnlyCounter() {
        @Override
        public long getCount() {
            return classLoadingMXBean.getTotalLoadedClassCount();
        }
    });

    meta = Metadata.builder()
            .withName(TOTAL_UNLOADED_CLASS_COUNT)
            .withType(MetricType.COUNTER)
            .withDisplayName("Total Unloaded Class Count")
            .withDescription(
                    "Displays the total number of classes unloaded since the Java virtual machine has started execution.")
            .build();
    registry.register(meta, new GetCountOnlyCounter() {
        @Override
        public long getCount() {
            return classLoadingMXBean.getUnloadedClassCount();
        }
    });

    meta = Metadata.builder()
            .withName(CURRENT_LOADED_CLASS_COUNT)
            .withType(MetricType.GAUGE)
            .withDisplayName("Current Loaded Class Count")
            .withDescription("Displays the number of classes that are currently loaded in the Java virtual machine.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return classLoadingMXBean.getLoadedClassCount();
        }
    });
}
 
Example 19
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void threadingMetrics(MetricRegistry registry) {
    ThreadMXBean thread = ManagementFactory.getThreadMXBean();

    Metadata meta = Metadata.builder()
            .withName(THREAD_COUNT)
            .withType(MetricType.GAUGE)
            .withDisplayName("Thread Count")
            .withDescription("Displays the current number of live threads including both daemon and non-daemon threads")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return thread.getThreadCount();
        }
    });

    meta = Metadata.builder()
            .withName(THREAD_DAEMON_COUNT)
            .withType(MetricType.GAUGE)
            .withDisplayName("Daemon Thread Count")
            .withDescription("Displays the current number of live daemon threads.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return thread.getDaemonThreadCount();
        }
    });

    meta = Metadata.builder()
            .withName(THREAD_MAX_COUNT)
            .withType(MetricType.GAUGE)
            .withDisplayName("Peak Thread Count")
            .withDescription("Displays the peak live thread count since the Java virtual machine started or peak was " +
                    "reset. This includes daemon and non-daemon threads.")
            .build();
    registry.register(meta, new Gauge() {
        @Override
        public Number getValue() {
            return thread.getPeakThreadCount();
        }
    });
}
 
Example 20
Source File: SmallRyeMetricsRecorder.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void micrometerJvmGcMetrics(MetricRegistry registry, ShutdownContext shutdownContext) {
    if (!ImageInfo.inImageCode()) {
        MicrometerGCMetrics gcMetrics = new MicrometerGCMetrics();

        registry.register(new ExtendedMetadataBuilder()
                .withName("jvm.gc.max.data.size")
                .withType(MetricType.GAUGE)
                .withUnit(MetricUnits.BYTES)
                .withDescription("Max size of old generation memory pool")
                .skipsScopeInOpenMetricsExportCompletely(true)
                .build(), new Gauge() {
                    @Override
                    public Number getValue() {
                        return gcMetrics.getMaxDataSize();
                    }
                });
        registry.register(new ExtendedMetadataBuilder()
                .withName("jvm.gc.live.data.size")
                .withType(MetricType.GAUGE)
                .withUnit(MetricUnits.BYTES)
                .withDescription("Size of old generation memory pool after a full GC")
                .skipsScopeInOpenMetricsExportCompletely(true)
                .build(), new Gauge() {
                    @Override
                    public Number getValue() {
                        return gcMetrics.getLiveDataSize();
                    }
                });
        registry.register(new ExtendedMetadataBuilder()
                .withName("jvm.gc.memory.promoted")
                .withType(MetricType.COUNTER)
                .withUnit(MetricUnits.BYTES)
                .withDescription(
                        "Count of positive increases in the size of the old generation memory pool before GC to after GC")
                .skipsScopeInOpenMetricsExportCompletely(true)
                .withOpenMetricsKeyOverride("jvm_gc_memory_promoted_bytes_total")
                .build(), new GetCountOnlyCounter() {
                    @Override
                    public long getCount() {
                        return gcMetrics.getPromotedBytes();
                    }
                });
        registry.register(new ExtendedMetadataBuilder()
                .withName("jvm.gc.memory.allocated")
                .withType(MetricType.COUNTER)
                .withUnit(MetricUnits.BYTES)
                .withDescription(
                        "Incremented for an increase in the size of the young generation memory pool after one GC to before the next")
                .skipsScopeInOpenMetricsExportCompletely(true)
                .withOpenMetricsKeyOverride("jvm_gc_memory_allocated_bytes_total")
                .build(), new GetCountOnlyCounter() {
                    @Override
                    public long getCount() {
                        return gcMetrics.getAllocatedBytes();
                    }
                });

        // start updating the metric values in a listener for GC events
        // Metrics that mimic the jvm.gc.pause timer will be registered lazily as GC events occur
        gcMetrics.startWatchingNotifications();
        shutdownContext.addShutdownTask(gcMetrics::cleanUp);
    }
}