OpenTelemetry Exporter Prometheus provides a metrics endpoint for Prometheus
npx @tessl/cli install tessl/npm-opentelemetry--exporter-prometheus@0.204.0OpenTelemetry Exporter Prometheus provides a metrics endpoint for Prometheus, enabling applications to expose collected OpenTelemetry metrics in Prometheus format through an HTTP endpoint. It serves as a bridge between OpenTelemetry's metric collection system and Prometheus monitoring infrastructure.
npm install @opentelemetry/exporter-prometheusimport { PrometheusExporter, PrometheusSerializer } from "@opentelemetry/exporter-prometheus";
import type { ExporterConfig } from "@opentelemetry/exporter-prometheus";For CommonJS:
const { PrometheusExporter, PrometheusSerializer } = require("@opentelemetry/exporter-prometheus");import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";
import { MeterProvider } from "@opentelemetry/sdk-metrics";
// Create and configure the Prometheus exporter
const exporter = new PrometheusExporter({
host: "0.0.0.0",
port: 9464,
endpoint: "/metrics"
});
// Register with MeterProvider
const meterProvider = new MeterProvider({
readers: [exporter]
});
// The exporter automatically starts an HTTP server on the configured port
// Prometheus can now scrape metrics from http://localhost:9464/metricsThe OpenTelemetry Prometheus Exporter consists of several key components:
Main class for serving OpenTelemetry metrics in Prometheus format via HTTP endpoint.
/**
* PrometheusExporter extends MetricReader to expose metrics via HTTP server
*/
class PrometheusExporter extends MetricReader {
/** Default configuration options */
static readonly DEFAULT_OPTIONS: {
host: undefined;
port: 9464;
endpoint: "/metrics";
prefix: "";
appendTimestamp: false;
withResourceConstantLabels: undefined;
};
/**
* Creates a new PrometheusExporter instance
* @param config - Optional configuration object
* @param callback - Optional callback invoked after server starts
*/
constructor(
config?: ExporterConfig,
callback?: (error: Error | void) => void
);
/** Starts the Prometheus export server */
startServer(): Promise<void>;
/** Stops the Prometheus export server */
stopServer(): Promise<void>;
/**
* Request handler for metrics endpoint
* @param _request - Incoming HTTP request
* @param response - HTTP response object
*/
getMetricsRequestHandler(
_request: IncomingMessage,
response: ServerResponse
): void;
/** Override method for force flush (no-op) */
onForceFlush(): Promise<void>;
/** Override method for shutdown, delegates to stopServer() */
onShutdown(): Promise<void>;
}Usage Examples:
import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";
// Basic usage with default configuration
const exporter = new PrometheusExporter();
// Custom configuration
const customExporter = new PrometheusExporter({
host: "localhost",
port: 8080,
endpoint: "/custom-metrics",
prefix: "myapp",
appendTimestamp: true
}, (error) => {
if (error) {
console.error("Failed to start Prometheus exporter:", error);
} else {
console.log("Prometheus exporter started successfully");
}
});
// Prevent automatic server start
const manualExporter = new PrometheusExporter({
preventServerStart: true
});
// Start server manually later
await manualExporter.startServer();Utility class for converting OpenTelemetry metrics to Prometheus text format.
/**
* PrometheusSerializer handles conversion of OpenTelemetry metrics to Prometheus format
*/
class PrometheusSerializer {
/**
* Creates a new PrometheusSerializer instance
* @param prefix - Optional prefix for metric names
* @param appendTimestamp - Whether to include timestamps (default false)
* @param withResourceConstantLabels - Optional regex for resource constant labels
*/
constructor(
prefix?: string,
appendTimestamp?: boolean,
withResourceConstantLabels?: RegExp
);
/**
* Serializes resource metrics to Prometheus text format
* @param resourceMetrics - OpenTelemetry resource metrics
* @returns Prometheus formatted text
*/
serialize(resourceMetrics: ResourceMetrics): string;
}Usage Examples:
import { PrometheusSerializer } from "@opentelemetry/exporter-prometheus";
import { ResourceMetrics } from "@opentelemetry/sdk-metrics";
// Basic serializer
const serializer = new PrometheusSerializer();
// Serializer with prefix and timestamps
const customSerializer = new PrometheusSerializer(
"myapp",
true,
/service_.+/ // Include service_* attributes as labels
);
// Convert metrics to Prometheus format
const resourceMetrics: ResourceMetrics = /* ... get from SDK ... */;
const prometheusText = serializer.serialize(resourceMetrics);
console.log(prometheusText);Configuration interface for customizing the Prometheus exporter behavior.
/**
* Configuration interface for PrometheusExporter
*/
interface ExporterConfig {
/** App prefix for metrics (default: '') */
prefix?: string;
/** Append timestamp to metrics (default: false) */
appendTimestamp?: boolean;
/** Endpoint path with preceding slash (default: '/metrics') */
endpoint?: string;
/** Server host (default: undefined - all interfaces) */
host?: string;
/** Port number for server (default: 9464) */
port?: number;
/** Prevent server from auto-starting (default: false) */
preventServerStart?: boolean;
/** Additional metric producers (experimental) */
metricProducers?: MetricProducer[];
/**
* Regex pattern for resource attributes as constant labels
* (default: undefined - no resource attributes applied)
*/
withResourceConstantLabels?: RegExp;
}Usage Examples:
import { PrometheusExporter, ExporterConfig } from "@opentelemetry/exporter-prometheus";
// Complete configuration example
const config: ExporterConfig = {
host: "0.0.0.0",
port: 9090,
endpoint: "/custom-metrics",
prefix: "myservice",
appendTimestamp: true,
withResourceConstantLabels: /service\.|telemetry\./,
preventServerStart: false
};
const exporter = new PrometheusExporter(config);The exporter supports configuration via environment variables:
// Environment variables take precedence over config object
process.env.OTEL_EXPORTER_PROMETHEUS_HOST = "127.0.0.1";
process.env.OTEL_EXPORTER_PROMETHEUS_PORT = "8080";
const exporter = new PrometheusExporter(); // Uses env vars// From @opentelemetry/sdk-metrics
interface ResourceMetrics {
resource: Resource;
scopeMetrics: ScopeMetrics[];
}
interface MetricProducer {
// Metric producer interface for additional metrics
}
// From Node.js http module
interface IncomingMessage {
url?: string;
// ... other Node.js http properties
}
interface ServerResponse {
statusCode: number;
setHeader(name: string, value: string): void;
end(data?: string): void;
// ... other Node.js http properties
}The exporter uses OpenTelemetry's diagnostic logging and error handling:
import { diag } from "@opentelemetry/api";
// Error handling during server operations
const exporter = new PrometheusExporter({}, (error) => {
if (error) {
console.error("Exporter error:", error);
// Handle server startup errors
}
});
// Errors during metric collection are logged via diag API
// and served as error messages in the responseCommon error scenarios: