Client for prometheus that provides comprehensive Prometheus metrics collection and exposition for Node.js applications
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
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.
/**
* A counter is a cumulative metric that represents a single numerical value that only ever goes up
*/
class Counter<T extends string = string> {
/**
* @param configuration Configuration when creating a Counter metric. Name and Help is required.
*/
constructor(configuration: CounterConfiguration<T>);
/**
* Increment for given labels
* @param labels Object with label keys and values
* @param value The number to increment with (default: 1)
*/
inc(labels: LabelValues<T>, value?: number): void;
/**
* Increment with value
* @param value The value to increment with (default: 1)
*/
inc(value?: number): void;
/**
* Increment with exemplars
* @param incData Object with labels, value and exemplars for an increase
*/
inc(incData: IncreaseDataWithExemplar<T>): void;
/**
* Get counter metric object
*/
get(): Promise<MetricObjectWithValues<MetricValue<T>>>;
/**
* Return the child for given labels
* @param values Label values
* @return Configured counter with given labels
*/
labels(...values: string[]): Counter.Internal;
/**
* Return the child for given labels
* @param labels Object with label keys and values
* @return Configured counter with given labels
*/
labels(labels: LabelValues<T>): Counter.Internal;
/**
* Reset counter values
*/
reset(): void;
/**
* Remove metrics for the given label values
* @param values Label values
*/
remove(...values: string[]): void;
/**
* Remove metrics for the given label values
* @param labels Object with label keys and values
*/
remove(labels: LabelValues<T>): void;
}
interface CounterConfiguration<T extends string> extends MetricConfiguration<T> {
collect?: CollectFunction<Counter<T>>;
}
interface IncreaseDataWithExemplar<T extends string> {
value?: number;
labels?: LabelValues<T>;
exemplarLabels?: LabelValues<T>;
}Usage Examples:
import { Counter } from "prom-client";
// Create a counter without labels
const httpRequestsTotal = new Counter({
name: "http_requests_total",
help: "Total number of HTTP requests",
});
// Create a counter with labels
const requestsByRoute = new Counter({
name: "http_requests_by_route_total",
help: "Total HTTP requests by route and status",
labelNames: ["route", "status_code"],
});
// Increment without labels
httpRequestsTotal.inc();
httpRequestsTotal.inc(5);
// Increment with labels
requestsByRoute.inc({ route: "/api/users", status_code: "200" });
requestsByRoute.inc({ route: "/api/posts", status_code: "404" }, 2);
// Use labeled child for better performance
const apiUserRequests = requestsByRoute.labels("/api/users", "200");
apiUserRequests.inc();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.
/**
* A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.
*/
class Gauge<T extends string = string> {
/**
* @param configuration Configuration when creating a Gauge metric. Name and Help is mandatory
*/
constructor(configuration: GaugeConfiguration<T>);
/**
* Increment gauge for given labels
* @param labels Object with label keys and values
* @param value The value to increment with (default: 1)
*/
inc(labels: LabelValues<T>, value?: number): void;
/**
* Increment gauge
* @param value The value to increment with (default: 1)
*/
inc(value?: number): void;
/**
* Decrement gauge
* @param labels Object with label keys and values
* @param value Value to decrement with (default: 1)
*/
dec(labels: LabelValues<T>, value?: number): void;
/**
* Decrement gauge
* @param value The value to decrement with (default: 1)
*/
dec(value?: number): void;
/**
* Set gauge value for labels
* @param labels Object with label keys and values
* @param value The value to set
*/
set(labels: LabelValues<T>, value: number): void;
/**
* Set gauge value
* @param value The value to set
*/
set(value: number): void;
/**
* Get gauge metric object
*/
get(): Promise<MetricObjectWithValues<MetricValue<T>>>;
/**
* Set gauge value to current epoch time in seconds
* @param labels Object with label keys and values
*/
setToCurrentTime(labels?: LabelValues<T>): void;
/**
* Start a timer. Calling the returned function will set the gauge's value
* to the observed duration in seconds.
* @param labels Object with label keys and values
* @return Function to invoke when timer should be stopped. The value it
* returns is the timed duration.
*/
startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number;
/**
* Return the child for given labels
* @param values Label values
* @return Configured gauge with given labels
*/
labels(...values: string[]): Gauge.Internal<T>;
/**
* Return the child for given labels
* @param labels Object with label keys and values
* @return Configured counter with given labels
*/
labels(labels: LabelValues<T>): Gauge.Internal<T>;
/**
* Reset gauge values
*/
reset(): void;
/**
* Remove metrics for the given label values
* @param values Label values
*/
remove(...values: string[]): void;
/**
* Remove metrics for the given label values
* @param labels Object with label keys and values
*/
remove(labels: LabelValues<T>): void;
}
interface GaugeConfiguration<T extends string> extends MetricConfiguration<T> {
collect?: CollectFunction<Gauge<T>>;
}Usage Examples:
import { Gauge } from "prom-client";
// Create a gauge for current memory usage
const memoryUsageBytes = new Gauge({
name: "memory_usage_bytes",
help: "Current memory usage in bytes",
});
// Create a gauge with labels for connection pools
const connectionPoolSize = new Gauge({
name: "connection_pool_size",
help: "Current connection pool size",
labelNames: ["database", "pool_type"],
});
// Set absolute values
memoryUsageBytes.set(process.memoryUsage().heapUsed);
connectionPoolSize.set({ database: "postgres", pool_type: "read" }, 10);
// Increment/decrement
connectionPoolSize.inc({ database: "postgres", pool_type: "read" });
connectionPoolSize.dec({ database: "postgres", pool_type: "read" }, 2);
// Timer functionality
const timer = memoryUsageBytes.startTimer();
// ... do some work
const duration = timer(); // Sets gauge to duration in seconds
// Set to current time
const lastProcessedTime = new Gauge({
name: "last_processed_timestamp_seconds",
help: "Timestamp when last item was processed",
});
lastProcessedTime.setToCurrentTime();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.
/**
* A histogram samples observations (usually things like request durations or response sizes) and counts them in configurable buckets
*/
class Histogram<T extends string = string> {
/**
* @param configuration Configuration when creating the Histogram. Name and Help is mandatory
*/
constructor(configuration: HistogramConfiguration<T>);
/**
* Observe value
* @param value The value to observe
*/
observe(value: number): void;
/**
* Observe value for given labels
* @param labels Object with label keys and values
* @param value The value to observe
*/
observe(labels: LabelValues<T>, value: number): void;
/**
* Observe with exemplars
* @param observeData Object with labels, value and exemplars for an observation
*/
observe(observeData: ObserveDataWithExemplar<T>): void;
/**
* Get histogram metric object
*/
get(): Promise<MetricObjectWithValues<MetricValueWithName<T>>>;
/**
* Start a timer. Calling the returned function will observe the duration in
* seconds in the histogram.
* @param labels Object with label keys and values
* @return Function to invoke when timer should be stopped. The value it
* returns is the timed duration.
*/
startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number;
/**
* Start a timer with exemplar. Calling the returned function will observe the duration in
* seconds in the histogram.
* @param labels Object with label keys and values
* @param exemplarLabels Object with label keys and values for exemplars
* @return Function to invoke when timer should be stopped. The value it
* returns is the timed duration.
*/
startTimer(
labels?: LabelValues<T>,
exemplarLabels?: LabelValues<T>
): (labels?: LabelValues<T>, exemplarLabels?: LabelValues<T>) => number;
/**
* Reset histogram values
*/
reset(): void;
/**
* Initialize the metrics for the given combination of labels to zero
*/
zero(labels: LabelValues<T>): void;
/**
* Return the child for given labels
* @param values Label values
* @return Configured histogram with given labels
*/
labels(...values: string[]): Histogram.Internal<T>;
/**
* Return the child for given labels
* @param labels Object with label keys and values
* @return Configured counter with given labels
*/
labels(labels: LabelValues<T>): Histogram.Internal<T>;
/**
* Remove metrics for the given label values
* @param values Label values
*/
remove(...values: string[]): void;
/**
* Remove metrics for the given label values
* @param labels Object with label keys and values
*/
remove(labels: LabelValues<T>): void;
}
interface HistogramConfiguration<T extends string> extends MetricConfiguration<T> {
buckets?: number[];
collect?: CollectFunction<Histogram<T>>;
}
interface ObserveDataWithExemplar<T extends string> {
value: number;
labels?: LabelValues<T>;
exemplarLabels?: LabelValues<T>;
}Usage Examples:
import { Histogram, linearBuckets } from "prom-client";
// Create a histogram for request durations
const httpRequestDuration = new Histogram({
name: "http_request_duration_seconds",
help: "Duration of HTTP requests in seconds",
labelNames: ["method", "route"],
buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10], // Default buckets
});
// Create a histogram with custom buckets
const payloadSize = new Histogram({
name: "http_request_size_bytes",
help: "Size of HTTP request payloads",
buckets: linearBuckets(100, 100, 10), // 100, 200, 300, ..., 1000
});
// Observe values directly
httpRequestDuration.observe({ method: "GET", route: "/api/users" }, 0.543);
payloadSize.observe(1024);
// Use timer functionality
const timer = httpRequestDuration.startTimer({ method: "POST", route: "/api/users" });
// ... handle request
const duration = timer(); // Automatically observes the duration
// Using labeled child for better performance
const getUserTimer = httpRequestDuration.labels("GET", "/api/users");
const getUserRequestTimer = getUserTimer.startTimer();
// ... handle request
getUserRequestTimer();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.
/**
* A summary samples observations
*/
class Summary<T extends string = string> {
/**
* @param configuration Configuration when creating Summary metric. Name and Help is mandatory
*/
constructor(configuration: SummaryConfiguration<T>);
/**
* Observe value in summary
* @param value The value to observe
*/
observe(value: number): void;
/**
* Observe value for given labels
* @param labels Object with label keys and values
* @param value Value to observe
*/
observe(labels: LabelValues<T>, value: number): void;
/**
* Get summary metric object
*/
get(): Promise<MetricObjectWithValues<MetricValueWithName<T>>>;
/**
* Start a timer. Calling the returned function will observe the duration in
* seconds in the summary.
* @param labels Object with label keys and values
* @return Function to invoke when timer should be stopped
*/
startTimer(labels?: LabelValues<T>): (labels?: LabelValues<T>) => number;
/**
* Reset all values in the summary
*/
reset(): void;
/**
* Return the child for given labels
* @param values Label values
* @return Configured summary with given labels
*/
labels(...values: string[]): Summary.Internal<T>;
/**
* Return the child for given labels
* @param labels Object with label keys and values
* @return Configured counter with given labels
*/
labels(labels: LabelValues<T>): Summary.Internal<T>;
/**
* Remove metrics for the given label values
* @param values Label values
*/
remove(...values: string[]): void;
/**
* Remove metrics for the given label values
* @param labels Object with label keys and values
*/
remove(labels: LabelValues<T>): void;
}
interface SummaryConfiguration<T extends string> extends MetricConfiguration<T> {
percentiles?: number[];
maxAgeSeconds?: number;
ageBuckets?: number;
pruneAgedBuckets?: boolean;
compressCount?: number;
collect?: CollectFunction<Summary<T>>;
}Usage Examples:
import { Summary } from "prom-client";
// Create a summary with default quantiles (0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999)
const httpRequestDuration = new Summary({
name: "http_request_duration_seconds",
help: "Duration of HTTP requests in seconds",
labelNames: ["method", "route"],
});
// Create a summary with custom quantiles and time window
const responseTime = new Summary({
name: "api_response_time_seconds",
help: "API response time in seconds",
percentiles: [0.5, 0.9, 0.95, 0.99],
maxAgeSeconds: 600, // 10 minute time window
ageBuckets: 5, // 5 age buckets (2 minutes each)
});
// Observe values
httpRequestDuration.observe({ method: "GET", route: "/api/users" }, 0.234);
responseTime.observe(0.156);
// Use timer functionality
const timer = httpRequestDuration.startTimer({ method: "POST", route: "/api/data" });
// ... process request
const duration = timer();
// Using labeled child
const getUserSummary = httpRequestDuration.labels("GET", "/api/users");
getUserSummary.observe(0.123);interface MetricConfiguration<T extends string> {
name: string;
help: string;
labelNames?: T[] | readonly T[];
registers?: Registry[];
aggregator?: Aggregator;
collect?: CollectFunction<any>;
enableExemplars?: boolean;
}
type LabelValues<T extends string> = Partial<Record<T, string | number>>;
type CollectFunction<T> = (this: T) => void | Promise<void>;
type Aggregator = 'omit' | 'sum' | 'first' | 'min' | 'max' | 'average';
interface MetricValue<T extends string> {
value: number;
labels: LabelValues<T>;
}
interface MetricValueWithName<T extends string> extends MetricValue<T> {
metricName?: string;
}
interface MetricObjectWithValues<T extends MetricValue<string>> {
name: string;
help: string;
type: MetricType;
aggregator: Aggregator;
values: T[];
}
enum MetricType {
Counter,
Gauge,
Histogram,
Summary,
}Install with Tessl CLI
npx tessl i tessl/npm-prom-client