001package io.prometheus.metrics.expositionformats;
002
003import io.prometheus.metrics.annotations.StableApi;
004import io.prometheus.metrics.config.EscapingScheme;
005import io.prometheus.metrics.model.snapshots.MetricSnapshots;
006import java.io.ByteArrayOutputStream;
007import java.io.IOException;
008import java.io.OutputStream;
009import javax.annotation.Nullable;
010
011@StableApi
012public interface ExpositionFormatWriter {
013  boolean accepts(@Nullable String acceptHeader);
014
015  /** Writes the given metric snapshots to the output stream using the specified escaping scheme. */
016  void write(OutputStream out, MetricSnapshots metricSnapshots, EscapingScheme escapingScheme)
017      throws IOException;
018
019  /** Writes the given metric snapshots to the output stream using the default escaping scheme. */
020  default void write(OutputStream out, MetricSnapshots metricSnapshots) throws IOException {
021    write(out, metricSnapshots, EscapingScheme.DEFAULT);
022  }
023
024  /** Converts the metric snapshots to a debug string using the specified escaping scheme. */
025  // toString with Charset is only available in Java 10+, but we want to support Java 8
026  @SuppressWarnings("JdkObsolete")
027  default String toDebugString(MetricSnapshots metricSnapshots, EscapingScheme escapingScheme) {
028    ByteArrayOutputStream out = new ByteArrayOutputStream();
029    try {
030      write(out, metricSnapshots, escapingScheme);
031      return out.toString("UTF-8");
032    } catch (IOException e) {
033      throw new RuntimeException(e);
034    }
035  }
036
037  /** Converts the metric snapshots to a debug string using the default escaping scheme. */
038  default String toDebugString(MetricSnapshots metricSnapshots) {
039    return toDebugString(metricSnapshots, EscapingScheme.DEFAULT);
040  }
041
042  String getContentType();
043
044  /**
045   * Returns true if the writer is available. If false, the writer will throw an exception if used.
046   */
047  default boolean isAvailable() {
048    return true;
049  }
050}