cloudflare-worker-metrics
v1.4.0
Published
Lightweight metrics collection for Cloudflare Workers
Readme
cloudflare-worker-metrics
Lightweight metrics collection for Cloudflare Workers.
Metrics are aggregated during invocation and then finally flushed via logs. The cloudflare-worker-metrics-exporter then reads those logs and emits them to an OTEL endpoint.
Usage
import { metrics } from 'cloudflare-worker-metrics';
export default {
async fetch(request, env, ctx) {
metrics.count('http_requests', 1, { method: request.method });
metrics.gauge('connections_active', getActiveCount());
metrics.histogram('response_duration', elapsed, { endpoint: '/api' });
const response = await handleRequest(request);
metrics.flush();
return response;
},
};Type-safe usage
Define a registry of metric names and their tag shapes, then create a typed metrics instance:
import { createMetrics } from 'cloudflare-worker-metrics';
type MyMetrics = {
http_request_count: { method: string; route: string }
http_response_duration_ms: { method: string; route: string; status: number }
db_query_duration_ms: { operation: string; table: string }
}
const metrics = createMetrics<MyMetrics>({
globalTags: { build_version: '1.0.0' },
});
metrics.count('http_request_count', 1, { method: 'GET', route: '/api/health' });
metrics.histogram('http_response_duration_ms', 42, { method: 'GET', route: '/api/health', status: 200 });
metrics.flush();createMetrics<T>(options?)
Create a typed metrics instance. T maps metric names to their expected tag shapes.
Only registered names are accepted and tags are type-checked per metric.
Options:
globalTags— tags automatically merged into every emission (metric-specific tags take precedence).
API
metrics.count(name, value?, tags?)
Increment a counter. Values with the same name+tags are summed.
metrics.gauge(name, value, tags?)
Set a gauge. Last write wins for the same name+tags.
metrics.histogram(name, value, tags?)
Record a histogram observation. Each call emits a raw histogram entry.
metrics.flush()
Flush all metrics to console.log as cwm- prefixed JSON. Auto-splits at 250 KiB.
