CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-opentelemetry--exporter-prometheus

OpenTelemetry Exporter Prometheus provides a metrics endpoint for Prometheus

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

OpenTelemetry Exporter Prometheus

OpenTelemetry 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.

Package Information

  • Package Name: @opentelemetry/exporter-prometheus
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @opentelemetry/exporter-prometheus

Core Imports

import { PrometheusExporter, PrometheusSerializer } from "@opentelemetry/exporter-prometheus";
import type { ExporterConfig } from "@opentelemetry/exporter-prometheus";

For CommonJS:

const { PrometheusExporter, PrometheusSerializer } = require("@opentelemetry/exporter-prometheus");

Basic Usage

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/metrics

Architecture

The OpenTelemetry Prometheus Exporter consists of several key components:

  • PrometheusExporter: Main class that creates an HTTP server to expose metrics in Prometheus format
  • PrometheusSerializer: Utility class for converting OpenTelemetry metrics to Prometheus text format
  • HTTP Server: Built-in Node.js HTTP server that serves metrics on demand
  • Automatic Conversion: Handles metric type mapping from OpenTelemetry to Prometheus formats (counters, gauges, histograms)

Capabilities

Prometheus Exporter

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();

Prometheus Serializer

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

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);

Environment Variables

The exporter supports configuration via environment variables:

  • OTEL_EXPORTER_PROMETHEUS_HOST - Overrides host configuration
  • OTEL_EXPORTER_PROMETHEUS_PORT - Overrides port configuration
// 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

Types

External Dependencies

// 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
}

Error Handling

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 response

Common error scenarios:

  • Port already in use during server startup
  • Invalid metric collection causing serialization errors
  • Network errors during metric serving
  • Invalid configuration parameters

Install with Tessl CLI

npx tessl i tessl/npm-opentelemetry--exporter-prometheus
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@opentelemetry/exporter-prometheus@0.204.x
Publish Source
CLI
Badge
tessl/npm-opentelemetry--exporter-prometheus badge