001package io.prometheus.client; 002 003import java.util.ArrayList; 004import java.util.Collections; 005import java.util.List; 006 007/** 008 * Counter metric family, for custom collectors and exporters. 009 * <p> 010 * Most users want a normal {@link Counter} instead. 011 * 012 * Example usage: 013 * <pre> 014 * {@code 015 * class YourCustomCollector extends Collector { 016 * List<MetricFamilySamples> collect() { 017 * List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); 018 * // With no labels. 019 * mfs.add(new CounterMetricFamily("my_counter_total", "help", 42)); 020 * // With labels 021 * CounterMetricFamily labeledCounter = new CounterMetricFamily("my_other_counter_total", "help", Arrays.asList("labelname")); 022 * labeledCounter.addMetric(Arrays.asList("foo"), 4); 023 * labeledCounter.addMetric(Arrays.asList("bar"), 5); 024 * mfs.add(labeledCounter); 025 * return mfs; 026 * } 027 * } 028 * } 029 * </pre> 030 */ 031public class CounterMetricFamily extends Collector.MetricFamilySamples { 032 033 private final List<String> labelNames; 034 035 public CounterMetricFamily(String name, String help, double value) { 036 super(name, Collector.Type.COUNTER, help, new ArrayList<Sample>()); 037 labelNames = Collections.emptyList(); 038 samples.add( 039 new Sample( 040 name, 041 labelNames, 042 Collections.<String>emptyList(), 043 value)); 044 } 045 046 public CounterMetricFamily(String name, String help, List<String> labelNames) { 047 super(name, Collector.Type.COUNTER, help, new ArrayList<Sample>()); 048 this.labelNames = labelNames; 049 } 050 051 public CounterMetricFamily addMetric(List<String> labelValues, double value) { 052 if (labelValues.size() != labelNames.size()) { 053 throw new IllegalArgumentException("Incorrect number of labels."); 054 } 055 samples.add(new Sample(name, labelNames, labelValues, value)); 056 return this; 057 } 058}