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