Metrics Docs
Cloudflare Workers
Send metrics from a Cloudflare Worker into Distlang Metrics using @distlang/client.
Store the token as a secret
Add your Distlang token to the Worker environment:
npx wrangler secret put DISTLANG_ACCESS_TOKEN
Example Worker
import { createDistlangClient } from "@distlang/client";
const client = createDistlangClient();
export default {
async fetch(request, env, ctx) {
const startedAt = Date.now();
const metrics = client.metrics.createRecorder({
accessToken: env.DISTLANG_ACCESS_TOKEN,
metricSet: "cloudflare-worker",
definitions: {
requestCount: "counter",
latencyMs: "histogram",
},
});
metrics.requestCount.inc({ method: request.method, status: "200" });
metrics.latencyMs.observe(Date.now() - startedAt, { method: request.method });
ctx.waitUntil(metrics.flush());
return new Response("ok");
},
};
Why use waitUntil
Workers can finish quickly. ctx.waitUntil(metrics.flush()) lets the flush continue after the response is returned, which keeps metrics off the main response path while still giving the write time to complete.
If you need the strongest request-by-request guarantee, you can still await metrics.flush() directly, but waitUntil(...) is the better default for normal Worker request metrics.
Notes
- Keep labels low-cardinality
- Reuse a stable
metricSetname for the service - Start with a small set of counters and histograms before adding dimensions