001package io.prometheus.metrics.exporter.servlet.javax; 002 003import io.prometheus.metrics.config.PrometheusProperties; 004import io.prometheus.metrics.exporter.common.PrometheusScrapeHandler; 005import io.prometheus.metrics.model.registry.PrometheusRegistry; 006import java.io.IOException; 007import javax.servlet.http.HttpServlet; 008import javax.servlet.http.HttpServletRequest; 009import javax.servlet.http.HttpServletResponse; 010 011/** 012 * This class extends HttpServlet to create a servlet for exporting Prometheus metrics. It uses a 013 * PrometheusScrapeHandler to handle HTTP GET requests and export metrics. The servlet can be 014 * configured with custom PrometheusProperties and a PrometheusRegistry. 015 */ 016public class PrometheusMetricsServlet extends HttpServlet { 017 018 private static final long serialVersionUID = 0L; 019 020 private final PrometheusScrapeHandler handler; 021 022 /** Default constructor. Uses the default PrometheusProperties and PrometheusRegistry. */ 023 public PrometheusMetricsServlet() { 024 this(PrometheusProperties.get(), PrometheusRegistry.defaultRegistry); 025 } 026 027 /** 028 * Constructor with a custom PrometheusRegistry. Uses the default PrometheusProperties. 029 * 030 * @param registry the PrometheusRegistry to use 031 */ 032 public PrometheusMetricsServlet(PrometheusRegistry registry) { 033 this(PrometheusProperties.get(), registry); 034 } 035 036 /** 037 * Constructor with custom PrometheusProperties. Uses the default PrometheusRegistry. 038 * 039 * @param config the PrometheusProperties to use 040 */ 041 public PrometheusMetricsServlet(PrometheusProperties config) { 042 this(config, PrometheusRegistry.defaultRegistry); 043 } 044 045 /** 046 * Constructor with custom PrometheusProperties and PrometheusRegistry. 047 * 048 * @param config the PrometheusProperties to use 049 * @param registry the PrometheusRegistry to use 050 */ 051 public PrometheusMetricsServlet(PrometheusProperties config, PrometheusRegistry registry) { 052 this.handler = new PrometheusScrapeHandler(config, registry); 053 } 054 055 /** 056 * Handles HTTP GET requests. Exports Prometheus metrics by delegating to the 057 * PrometheusScrapeHandler. 058 * 059 * @param request the HttpServletRequest 060 * @param response the HttpServletResponse 061 * @throws IOException if an I/O error occurs 062 */ 063 @Override 064 protected void doGet(HttpServletRequest request, HttpServletResponse response) 065 throws IOException { 066 handler.handleRequest(new HttpExchangeAdapter(request, response)); 067 } 068}