or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cluster.mddefault-metrics.mdindex.mdmetrics.mdpushgateway.mdregistry.md

metrics.mddocs/

0

# Metric Types

1

2

prom-client implements the four core Prometheus metric types: Counter, Gauge, Histogram, and Summary. Each metric type serves specific measurement use cases and provides different aggregation semantics in Prometheus.

3

4

## Capabilities

5

6

### Counter

7

8

A counter is a cumulative metric that represents a single numerical value that only ever goes up. Counters are typically used for tracking totals like requests served, tasks completed, or errors occurred.

9

10

```typescript { .api }

11

/**

12

* A counter is a cumulative metric that represents a single numerical value that only ever goes up

13

*/

14

class Counter<T extends string = string> {

15

/**

16

* @param configuration Configuration when creating a Counter metric. Name and Help is required.

17

*/

18

constructor(configuration: CounterConfiguration<T>);

19

20

/**

21

* Increment for given labels

22

* @param labels Object with label keys and values

23

* @param value The number to increment with (default: 1)

24

*/

25

inc(labels: LabelValues<T>, value?: number): void;

26

27

/**

28

* Increment with value

29

* @param value The value to increment with (default: 1)

30

*/

31

inc(value?: number): void;

32

33

/**

34

* Increment with exemplars

35

* @param incData Object with labels, value and exemplars for an increase

36

*/

37

inc(incData: IncreaseDataWithExemplar<T>): void;

38

39

/**

40

* Get counter metric object

41

*/

42

get(): Promise<MetricObjectWithValues<MetricValue<T>>>;

43

44

/**

45

* Return the child for given labels

46

* @param values Label values

47

* @return Configured counter with given labels

48

*/

49

labels(...values: string[]): Counter.Internal;

50

51

/**

52

* Return the child for given labels

53

* @param labels Object with label keys and values

54

* @return Configured counter with given labels

55

*/

56

labels(labels: LabelValues<T>): Counter.Internal;

57

58

/**

59

* Reset counter values

60

*/

61

reset(): void;

62

63

/**

64

* Remove metrics for the given label values

65

* @param values Label values

66

*/

67

remove(...values: string[]): void;

68

69

/**

70

* Remove metrics for the given label values

71

* @param labels Object with label keys and values

72

*/

73

remove(labels: LabelValues<T>): void;

74

}

75

76

interface CounterConfiguration<T extends string> extends MetricConfiguration<T> {

77

collect?: CollectFunction<Counter<T>>;

78

}

79

80

interface IncreaseDataWithExemplar<T extends string> {

81

value?: number;

82

labels?: LabelValues<T>;

83

exemplarLabels?: LabelValues<T>;

84

}

85

```

86

87

**Usage Examples:**

88

89

```typescript

90

import { Counter } from "prom-client";

91

92

// Create a counter without labels

93

const httpRequestsTotal = new Counter({

94

name: "http_requests_total",

95

help: "Total number of HTTP requests",

96

});

97

98

// Create a counter with labels

99

const requestsByRoute = new Counter({

100

name: "http_requests_by_route_total",

101

help: "Total HTTP requests by route and status",

102

labelNames: ["route", "status_code"],

103

});

104

105

// Increment without labels

106

httpRequestsTotal.inc();

107

httpRequestsTotal.inc(5);

108

109

// Increment with labels

110

requestsByRoute.inc({ route: "/api/users", status_code: "200" });

111

requestsByRoute.inc({ route: "/api/posts", status_code: "404" }, 2);

112

113

// Use labeled child for better performance

114

const apiUserRequests = requestsByRoute.labels("/api/users", "200");

115

apiUserRequests.inc();

116

```

117

118

### Gauge

119

120

A gauge is a metric that represents a single numerical value that can arbitrarily go up and down. Gauges are typically used for measured values like temperatures, current memory usage, or the number of concurrent requests.

121

122

```typescript { .api }

123

/**

124

* A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.

125

*/

126

class Gauge<T extends string = string> {

127

/**

128

* @param configuration Configuration when creating a Gauge metric. Name and Help is mandatory

129

*/

130

constructor(configuration: GaugeConfiguration<T>);

131

132

/**

133

* Increment gauge for given labels

134

* @param labels Object with label keys and values

135

* @param value The value to increment with (default: 1)

136

*/

137

inc(labels: LabelValues<T>, value?: number): void;

138

139

/**

140

* Increment gauge

141

* @param value The value to increment with (default: 1)

142

*/

143

inc(value?: number): void;

144

145

/**

146

* Decrement gauge

147

* @param labels Object with label keys and values

148

* @param value Value to decrement with (default: 1)

149

*/

150

dec(labels: LabelValues<T>, value?: number): void;

151

152

/**

153

* Decrement gauge

154

* @param value The value to decrement with (default: 1)

155

*/

156

dec(value?: number): void;

157

158

/**

159

* Set gauge value for labels

160

* @param labels Object with label keys and values

161

* @param value The value to set

162

*/

163

set(labels: LabelValues<T>, value: number): void;

164

165

/**

166

* Set gauge value

167

* @param value The value to set

168

*/

169

set(value: number): void;

170

171

/**

172

* Get gauge metric object

173

*/

174

get(): Promise<MetricObjectWithValues<MetricValue<T>>>;

175

176

/**

177

* Set gauge value to current epoch time in seconds

178

* @param labels Object with label keys and values

179

*/

180

setToCurrentTime(labels?: LabelValues<T>): void;

181

182

/**

183

* Start a timer. Calling the returned function will set the gauge's value

184

* to the observed duration in seconds.

185

* @param labels Object with label keys and values

186

* @return Function to invoke when timer should be stopped. The value it

187

* returns is the timed duration.

188

*/

189

startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number;

190

191

/**

192

* Return the child for given labels

193

* @param values Label values

194

* @return Configured gauge with given labels

195

*/

196

labels(...values: string[]): Gauge.Internal<T>;

197

198

/**

199

* Return the child for given labels

200

* @param labels Object with label keys and values

201

* @return Configured counter with given labels

202

*/

203

labels(labels: LabelValues<T>): Gauge.Internal<T>;

204

205

/**

206

* Reset gauge values

207

*/

208

reset(): void;

209

210

/**

211

* Remove metrics for the given label values

212

* @param values Label values

213

*/

214

remove(...values: string[]): void;

215

216

/**

217

* Remove metrics for the given label values

218

* @param labels Object with label keys and values

219

*/

220

remove(labels: LabelValues<T>): void;

221

}

222

223

interface GaugeConfiguration<T extends string> extends MetricConfiguration<T> {

224

collect?: CollectFunction<Gauge<T>>;

225

}

226

```

227

228

**Usage Examples:**

229

230

```typescript

231

import { Gauge } from "prom-client";

232

233

// Create a gauge for current memory usage

234

const memoryUsageBytes = new Gauge({

235

name: "memory_usage_bytes",

236

help: "Current memory usage in bytes",

237

});

238

239

// Create a gauge with labels for connection pools

240

const connectionPoolSize = new Gauge({

241

name: "connection_pool_size",

242

help: "Current connection pool size",

243

labelNames: ["database", "pool_type"],

244

});

245

246

// Set absolute values

247

memoryUsageBytes.set(process.memoryUsage().heapUsed);

248

connectionPoolSize.set({ database: "postgres", pool_type: "read" }, 10);

249

250

// Increment/decrement

251

connectionPoolSize.inc({ database: "postgres", pool_type: "read" });

252

connectionPoolSize.dec({ database: "postgres", pool_type: "read" }, 2);

253

254

// Timer functionality

255

const timer = memoryUsageBytes.startTimer();

256

// ... do some work

257

const duration = timer(); // Sets gauge to duration in seconds

258

259

// Set to current time

260

const lastProcessedTime = new Gauge({

261

name: "last_processed_timestamp_seconds",

262

help: "Timestamp when last item was processed",

263

});

264

lastProcessedTime.setToCurrentTime();

265

```

266

267

### Histogram

268

269

A histogram samples observations (usually things like request durations or response sizes) and counts them in configurable buckets. It also provides a sum of all observed values and a count of observations.

270

271

```typescript { .api }

272

/**

273

* A histogram samples observations (usually things like request durations or response sizes) and counts them in configurable buckets

274

*/

275

class Histogram<T extends string = string> {

276

/**

277

* @param configuration Configuration when creating the Histogram. Name and Help is mandatory

278

*/

279

constructor(configuration: HistogramConfiguration<T>);

280

281

/**

282

* Observe value

283

* @param value The value to observe

284

*/

285

observe(value: number): void;

286

287

/**

288

* Observe value for given labels

289

* @param labels Object with label keys and values

290

* @param value The value to observe

291

*/

292

observe(labels: LabelValues<T>, value: number): void;

293

294

/**

295

* Observe with exemplars

296

* @param observeData Object with labels, value and exemplars for an observation

297

*/

298

observe(observeData: ObserveDataWithExemplar<T>): void;

299

300

/**

301

* Get histogram metric object

302

*/

303

get(): Promise<MetricObjectWithValues<MetricValueWithName<T>>>;

304

305

/**

306

* Start a timer. Calling the returned function will observe the duration in

307

* seconds in the histogram.

308

* @param labels Object with label keys and values

309

* @return Function to invoke when timer should be stopped. The value it

310

* returns is the timed duration.

311

*/

312

startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number;

313

314

/**

315

* Start a timer with exemplar. Calling the returned function will observe the duration in

316

* seconds in the histogram.

317

* @param labels Object with label keys and values

318

* @param exemplarLabels Object with label keys and values for exemplars

319

* @return Function to invoke when timer should be stopped. The value it

320

* returns is the timed duration.

321

*/

322

startTimer(

323

labels?: LabelValues<T>,

324

exemplarLabels?: LabelValues<T>

325

): (labels?: LabelValues<T>, exemplarLabels?: LabelValues<T>) => number;

326

327

/**

328

* Reset histogram values

329

*/

330

reset(): void;

331

332

/**

333

* Initialize the metrics for the given combination of labels to zero

334

*/

335

zero(labels: LabelValues<T>): void;

336

337

/**

338

* Return the child for given labels

339

* @param values Label values

340

* @return Configured histogram with given labels

341

*/

342

labels(...values: string[]): Histogram.Internal<T>;

343

344

/**

345

* Return the child for given labels

346

* @param labels Object with label keys and values

347

* @return Configured counter with given labels

348

*/

349

labels(labels: LabelValues<T>): Histogram.Internal<T>;

350

351

/**

352

* Remove metrics for the given label values

353

* @param values Label values

354

*/

355

remove(...values: string[]): void;

356

357

/**

358

* Remove metrics for the given label values

359

* @param labels Object with label keys and values

360

*/

361

remove(labels: LabelValues<T>): void;

362

}

363

364

interface HistogramConfiguration<T extends string> extends MetricConfiguration<T> {

365

buckets?: number[];

366

collect?: CollectFunction<Histogram<T>>;

367

}

368

369

interface ObserveDataWithExemplar<T extends string> {

370

value: number;

371

labels?: LabelValues<T>;

372

exemplarLabels?: LabelValues<T>;

373

}

374

```

375

376

**Usage Examples:**

377

378

```typescript

379

import { Histogram, linearBuckets } from "prom-client";

380

381

// Create a histogram for request durations

382

const httpRequestDuration = new Histogram({

383

name: "http_request_duration_seconds",

384

help: "Duration of HTTP requests in seconds",

385

labelNames: ["method", "route"],

386

buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10], // Default buckets

387

});

388

389

// Create a histogram with custom buckets

390

const payloadSize = new Histogram({

391

name: "http_request_size_bytes",

392

help: "Size of HTTP request payloads",

393

buckets: linearBuckets(100, 100, 10), // 100, 200, 300, ..., 1000

394

});

395

396

// Observe values directly

397

httpRequestDuration.observe({ method: "GET", route: "/api/users" }, 0.543);

398

payloadSize.observe(1024);

399

400

// Use timer functionality

401

const timer = httpRequestDuration.startTimer({ method: "POST", route: "/api/users" });

402

// ... handle request

403

const duration = timer(); // Automatically observes the duration

404

405

// Using labeled child for better performance

406

const getUserTimer = httpRequestDuration.labels("GET", "/api/users");

407

const getUserRequestTimer = getUserTimer.startTimer();

408

// ... handle request

409

getUserRequestTimer();

410

```

411

412

### Summary

413

414

A summary samples observations (like request durations and response sizes) and provides configurable quantiles over a sliding time window, along with the total count and sum of observations.

415

416

```typescript { .api }

417

/**

418

* A summary samples observations

419

*/

420

class Summary<T extends string = string> {

421

/**

422

* @param configuration Configuration when creating Summary metric. Name and Help is mandatory

423

*/

424

constructor(configuration: SummaryConfiguration<T>);

425

426

/**

427

* Observe value in summary

428

* @param value The value to observe

429

*/

430

observe(value: number): void;

431

432

/**

433

* Observe value for given labels

434

* @param labels Object with label keys and values

435

* @param value Value to observe

436

*/

437

observe(labels: LabelValues<T>, value: number): void;

438

439

/**

440

* Get summary metric object

441

*/

442

get(): Promise<MetricObjectWithValues<MetricValueWithName<T>>>;

443

444

/**

445

* Start a timer. Calling the returned function will observe the duration in

446

* seconds in the summary.

447

* @param labels Object with label keys and values

448

* @return Function to invoke when timer should be stopped

449

*/

450

startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number;

451

452

/**

453

* Reset all values in the summary

454

*/

455

reset(): void;

456

457

/**

458

* Return the child for given labels

459

* @param values Label values

460

* @return Configured summary with given labels

461

*/

462

labels(...values: string[]): Summary.Internal<T>;

463

464

/**

465

* Return the child for given labels

466

* @param labels Object with label keys and values

467

* @return Configured counter with given labels

468

*/

469

labels(labels: LabelValues<T>): Summary.Internal<T>;

470

471

/**

472

* Remove metrics for the given label values

473

* @param values Label values

474

*/

475

remove(...values: string[]): void;

476

477

/**

478

* Remove metrics for the given label values

479

* @param labels Object with label keys and values

480

*/

481

remove(labels: LabelValues<T>): void;

482

}

483

484

interface SummaryConfiguration<T extends string> extends MetricConfiguration<T> {

485

percentiles?: number[];

486

maxAgeSeconds?: number;

487

ageBuckets?: number;

488

pruneAgedBuckets?: boolean;

489

compressCount?: number;

490

collect?: CollectFunction<Summary<T>>;

491

}

492

```

493

494

**Usage Examples:**

495

496

```typescript

497

import { Summary } from "prom-client";

498

499

// Create a summary with default quantiles (0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999)

500

const httpRequestDuration = new Summary({

501

name: "http_request_duration_seconds",

502

help: "Duration of HTTP requests in seconds",

503

labelNames: ["method", "route"],

504

});

505

506

// Create a summary with custom quantiles and time window

507

const responseTime = new Summary({

508

name: "api_response_time_seconds",

509

help: "API response time in seconds",

510

percentiles: [0.5, 0.9, 0.95, 0.99],

511

maxAgeSeconds: 600, // 10 minute time window

512

ageBuckets: 5, // 5 age buckets (2 minutes each)

513

});

514

515

// Observe values

516

httpRequestDuration.observe({ method: "GET", route: "/api/users" }, 0.234);

517

responseTime.observe(0.156);

518

519

// Use timer functionality

520

const timer = httpRequestDuration.startTimer({ method: "POST", route: "/api/data" });

521

// ... process request

522

const duration = timer();

523

524

// Using labeled child

525

const getUserSummary = httpRequestDuration.labels("GET", "/api/users");

526

getUserSummary.observe(0.123);

527

```

528

529

## Shared Configuration

530

531

```typescript { .api }

532

interface MetricConfiguration<T extends string> {

533

name: string;

534

help: string;

535

labelNames?: T[] | readonly T[];

536

registers?: Registry[];

537

aggregator?: Aggregator;

538

collect?: CollectFunction<any>;

539

enableExemplars?: boolean;

540

}

541

542

type LabelValues<T extends string> = Partial<Record<T, string | number>>;

543

type CollectFunction<T> = (this: T) => void | Promise<void>;

544

type Aggregator = 'omit' | 'sum' | 'first' | 'min' | 'max' | 'average';

545

546

interface MetricValue<T extends string> {

547

value: number;

548

labels: LabelValues<T>;

549

}

550

551

interface MetricValueWithName<T extends string> extends MetricValue<T> {

552

metricName?: string;

553

}

554

555

interface MetricObjectWithValues<T extends MetricValue<string>> {

556

name: string;

557

help: string;

558

type: MetricType;

559

aggregator: Aggregator;

560

values: T[];

561

}

562

563

enum MetricType {

564

Counter,

565

Gauge,

566

Histogram,

567

Summary,

568

}

569

```