001package io.prometheus.client.hotspot;
002
003import io.prometheus.client.Collector;
004import io.prometheus.client.CounterMetricFamily;
005import io.prometheus.client.GaugeMetricFamily;
006
007import java.lang.management.ManagementFactory;
008import java.lang.management.ClassLoadingMXBean;
009import java.util.ArrayList;
010import java.util.List;
011
012/**
013 * Exports metrics about JVM classloading.
014 * <p>
015 * Example usage:
016 * <pre>
017 * {@code
018 *   new ClassLoadingExports().register();
019 * }
020 * </pre>
021 * Example metrics being exported:
022 * <pre>
023 *   jvm_classes_loaded{} 1000
024 *   jvm_classes_loaded_total{} 2000
025 *   jvm_classes_unloaded_total{} 500
026 * </pre>
027 */
028public class ClassLoadingExports extends Collector {
029  private final ClassLoadingMXBean clBean;
030
031  public ClassLoadingExports() {
032    this(ManagementFactory.getClassLoadingMXBean());
033  }
034
035  public ClassLoadingExports(ClassLoadingMXBean clBean) {
036    this.clBean = clBean;
037  }
038
039  void addClassLoadingMetrics(List<MetricFamilySamples> sampleFamilies) {
040    sampleFamilies.add(new GaugeMetricFamily(
041          "jvm_classes_loaded",
042          "The number of classes that are currently loaded in the JVM",
043          clBean.getLoadedClassCount()));
044    sampleFamilies.add(new CounterMetricFamily(
045          "jvm_classes_loaded_total",
046          "The total number of classes that have been loaded since the JVM has started execution",
047          clBean.getTotalLoadedClassCount()));
048    sampleFamilies.add(new CounterMetricFamily(
049          "jvm_classes_unloaded_total",
050          "The total number of classes that have been unloaded since the JVM has started execution",
051          clBean.getUnloadedClassCount()));
052  }
053
054
055  public List<MetricFamilySamples> collect() {
056    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
057    addClassLoadingMetrics(mfs);
058    return mfs;
059  }
060}