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