001package io.prometheus.metrics.model.registry; 002 003import io.prometheus.metrics.model.snapshots.MetricSnapshot; 004import java.util.function.Predicate; 005 006/** 007 * To be registered with the Prometheus collector registry. See <i>Overall Structure</i> on <a 008 * href="https://prometheus.io/docs/instrumenting/writing_clientlibs/">https://prometheus.io/docs/instrumenting/writing_clientlibs/</a>. 009 */ 010@FunctionalInterface 011public interface Collector { 012 013 /** Called when the Prometheus server scrapes metrics. */ 014 MetricSnapshot collect(); 015 016 /** 017 * Provides Collector with the details of the request issued by Prometheus to allow multi-target 018 * pattern implementation Override to implement request dependent logic to provide MetricSnapshot 019 */ 020 default MetricSnapshot collect(PrometheusScrapeRequest scrapeRequest) { 021 return collect(); 022 } 023 024 /** 025 * Like {@link #collect()}, but returns {@code null} if {@code includedNames.test(name)} is {@code 026 * false}. 027 * 028 * <p>Override this if there is a more efficient way than first collecting the snapshot and then 029 * discarding it. 030 */ 031 default MetricSnapshot collect(Predicate<String> includedNames) { 032 MetricSnapshot result = collect(); 033 if (includedNames.test(result.getMetadata().getPrometheusName())) { 034 return result; 035 } else { 036 return null; 037 } 038 } 039 040 /** 041 * Like {@link #collect(Predicate)}, but with support for multi-target pattern. 042 * 043 * <p>Override this if there is a more efficient way than first collecting the snapshot and then 044 * discarding it. 045 */ 046 default MetricSnapshot collect( 047 Predicate<String> includedNames, PrometheusScrapeRequest scrapeRequest) { 048 MetricSnapshot result = collect(scrapeRequest); 049 if (includedNames.test(result.getMetadata().getPrometheusName())) { 050 return result; 051 } else { 052 return null; 053 } 054 } 055 056 /** 057 * This is called in two places: 058 * 059 * <ol> 060 * <li>During registration to check if a metric with that name already exists. 061 * <li>During scrape to check if this collector can be skipped because a name filter is present 062 * and the metric name is excluded. 063 * </ol> 064 * 065 * Returning {@code null} means checks are omitted (registration the metric always succeeds), and 066 * the collector is always scraped (the result is dropped after scraping if a name filter is 067 * present and the metric name is excluded). 068 * 069 * <p>If your metric has a name that does not change at runtime it is a good idea to overwrite 070 * this and return the name. 071 * 072 * <p>All metrics in {@code prometheus-metrics-core} override this. 073 */ 074 default String getPrometheusName() { 075 return null; 076 } 077}