or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# OpenTelemetry Exporter Prometheus

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: @opentelemetry/exporter-prometheus

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @opentelemetry/exporter-prometheus`

10

11

## Core Imports

12

13

```typescript

14

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

15

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

16

```

17

18

For CommonJS:

19

20

```javascript

21

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

22

```

23

24

## Basic Usage

25

26

```typescript

27

import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";

28

import { MeterProvider } from "@opentelemetry/sdk-metrics";

29

30

// Create and configure the Prometheus exporter

31

const exporter = new PrometheusExporter({

32

host: "0.0.0.0",

33

port: 9464,

34

endpoint: "/metrics"

35

});

36

37

// Register with MeterProvider

38

const meterProvider = new MeterProvider({

39

readers: [exporter]

40

});

41

42

// The exporter automatically starts an HTTP server on the configured port

43

// Prometheus can now scrape metrics from http://localhost:9464/metrics

44

```

45

46

## Architecture

47

48

The OpenTelemetry Prometheus Exporter consists of several key components:

49

50

- **PrometheusExporter**: Main class that creates an HTTP server to expose metrics in Prometheus format

51

- **PrometheusSerializer**: Utility class for converting OpenTelemetry metrics to Prometheus text format

52

- **HTTP Server**: Built-in Node.js HTTP server that serves metrics on demand

53

- **Automatic Conversion**: Handles metric type mapping from OpenTelemetry to Prometheus formats (counters, gauges, histograms)

54

55

## Capabilities

56

57

### Prometheus Exporter

58

59

Main class for serving OpenTelemetry metrics in Prometheus format via HTTP endpoint.

60

61

```typescript { .api }

62

/**

63

* PrometheusExporter extends MetricReader to expose metrics via HTTP server

64

*/

65

class PrometheusExporter extends MetricReader {

66

/** Default configuration options */

67

static readonly DEFAULT_OPTIONS: {

68

host: undefined;

69

port: 9464;

70

endpoint: "/metrics";

71

prefix: "";

72

appendTimestamp: false;

73

withResourceConstantLabels: undefined;

74

};

75

76

/**

77

* Creates a new PrometheusExporter instance

78

* @param config - Optional configuration object

79

* @param callback - Optional callback invoked after server starts

80

*/

81

constructor(

82

config?: ExporterConfig,

83

callback?: (error: Error | void) => void

84

);

85

86

/** Starts the Prometheus export server */

87

startServer(): Promise<void>;

88

89

/** Stops the Prometheus export server */

90

stopServer(): Promise<void>;

91

92

/**

93

* Request handler for metrics endpoint

94

* @param _request - Incoming HTTP request

95

* @param response - HTTP response object

96

*/

97

getMetricsRequestHandler(

98

_request: IncomingMessage,

99

response: ServerResponse

100

): void;

101

102

/** Override method for force flush (no-op) */

103

onForceFlush(): Promise<void>;

104

105

/** Override method for shutdown, delegates to stopServer() */

106

onShutdown(): Promise<void>;

107

}

108

```

109

110

**Usage Examples:**

111

112

```typescript

113

import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";

114

115

// Basic usage with default configuration

116

const exporter = new PrometheusExporter();

117

118

// Custom configuration

119

const customExporter = new PrometheusExporter({

120

host: "localhost",

121

port: 8080,

122

endpoint: "/custom-metrics",

123

prefix: "myapp",

124

appendTimestamp: true

125

}, (error) => {

126

if (error) {

127

console.error("Failed to start Prometheus exporter:", error);

128

} else {

129

console.log("Prometheus exporter started successfully");

130

}

131

});

132

133

// Prevent automatic server start

134

const manualExporter = new PrometheusExporter({

135

preventServerStart: true

136

});

137

138

// Start server manually later

139

await manualExporter.startServer();

140

```

141

142

### Prometheus Serializer

143

144

Utility class for converting OpenTelemetry metrics to Prometheus text format.

145

146

```typescript { .api }

147

/**

148

* PrometheusSerializer handles conversion of OpenTelemetry metrics to Prometheus format

149

*/

150

class PrometheusSerializer {

151

/**

152

* Creates a new PrometheusSerializer instance

153

* @param prefix - Optional prefix for metric names

154

* @param appendTimestamp - Whether to include timestamps (default false)

155

* @param withResourceConstantLabels - Optional regex for resource constant labels

156

*/

157

constructor(

158

prefix?: string,

159

appendTimestamp?: boolean,

160

withResourceConstantLabels?: RegExp

161

);

162

163

/**

164

* Serializes resource metrics to Prometheus text format

165

* @param resourceMetrics - OpenTelemetry resource metrics

166

* @returns Prometheus formatted text

167

*/

168

serialize(resourceMetrics: ResourceMetrics): string;

169

}

170

```

171

172

**Usage Examples:**

173

174

```typescript

175

import { PrometheusSerializer } from "@opentelemetry/exporter-prometheus";

176

import { ResourceMetrics } from "@opentelemetry/sdk-metrics";

177

178

// Basic serializer

179

const serializer = new PrometheusSerializer();

180

181

// Serializer with prefix and timestamps

182

const customSerializer = new PrometheusSerializer(

183

"myapp",

184

true,

185

/service_.+/ // Include service_* attributes as labels

186

);

187

188

// Convert metrics to Prometheus format

189

const resourceMetrics: ResourceMetrics = /* ... get from SDK ... */;

190

const prometheusText = serializer.serialize(resourceMetrics);

191

console.log(prometheusText);

192

```

193

194

### Configuration

195

196

Configuration interface for customizing the Prometheus exporter behavior.

197

198

```typescript { .api }

199

/**

200

* Configuration interface for PrometheusExporter

201

*/

202

interface ExporterConfig {

203

/** App prefix for metrics (default: '') */

204

prefix?: string;

205

206

/** Append timestamp to metrics (default: false) */

207

appendTimestamp?: boolean;

208

209

/** Endpoint path with preceding slash (default: '/metrics') */

210

endpoint?: string;

211

212

/** Server host (default: undefined - all interfaces) */

213

host?: string;

214

215

/** Port number for server (default: 9464) */

216

port?: number;

217

218

/** Prevent server from auto-starting (default: false) */

219

preventServerStart?: boolean;

220

221

/** Additional metric producers (experimental) */

222

metricProducers?: MetricProducer[];

223

224

/**

225

* Regex pattern for resource attributes as constant labels

226

* (default: undefined - no resource attributes applied)

227

*/

228

withResourceConstantLabels?: RegExp;

229

}

230

```

231

232

**Usage Examples:**

233

234

```typescript

235

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

236

237

// Complete configuration example

238

const config: ExporterConfig = {

239

host: "0.0.0.0",

240

port: 9090,

241

endpoint: "/custom-metrics",

242

prefix: "myservice",

243

appendTimestamp: true,

244

withResourceConstantLabels: /service\.|telemetry\./,

245

preventServerStart: false

246

};

247

248

const exporter = new PrometheusExporter(config);

249

```

250

251

## Environment Variables

252

253

The exporter supports configuration via environment variables:

254

255

- **OTEL_EXPORTER_PROMETHEUS_HOST** - Overrides host configuration

256

- **OTEL_EXPORTER_PROMETHEUS_PORT** - Overrides port configuration

257

258

```typescript

259

// Environment variables take precedence over config object

260

process.env.OTEL_EXPORTER_PROMETHEUS_HOST = "127.0.0.1";

261

process.env.OTEL_EXPORTER_PROMETHEUS_PORT = "8080";

262

263

const exporter = new PrometheusExporter(); // Uses env vars

264

```

265

266

## Types

267

268

### External Dependencies

269

270

```typescript { .api }

271

// From @opentelemetry/sdk-metrics

272

interface ResourceMetrics {

273

resource: Resource;

274

scopeMetrics: ScopeMetrics[];

275

}

276

277

interface MetricProducer {

278

// Metric producer interface for additional metrics

279

}

280

281

// From Node.js http module

282

interface IncomingMessage {

283

url?: string;

284

// ... other Node.js http properties

285

}

286

287

interface ServerResponse {

288

statusCode: number;

289

setHeader(name: string, value: string): void;

290

end(data?: string): void;

291

// ... other Node.js http properties

292

}

293

```

294

295

## Error Handling

296

297

The exporter uses OpenTelemetry's diagnostic logging and error handling:

298

299

```typescript

300

import { diag } from "@opentelemetry/api";

301

302

// Error handling during server operations

303

const exporter = new PrometheusExporter({}, (error) => {

304

if (error) {

305

console.error("Exporter error:", error);

306

// Handle server startup errors

307

}

308

});

309

310

// Errors during metric collection are logged via diag API

311

// and served as error messages in the response

312

```

313

314

Common error scenarios:

315

- Port already in use during server startup

316

- Invalid metric collection causing serialization errors

317

- Network errors during metric serving

318

- Invalid configuration parameters