@else42/cf-worker-otel

中文文档
0.2.2发布于 2026/04/05MITTypeScriptES Module零依赖近 30 天下载 2360

Lightweight OTLP metrics client for Cloudflare Workers

原始使用文档
文档目录12 节
  1. Install
  2. Quick Start
  3. SvelteKit on Cloudflare
  4. API
  5. createMetrics(config)
  6. metrics.counter(name, value, attributes?)
  7. metrics.gauge(name, value, attributes?)
  8. metrics.histogram(name, value, attributes?)
  9. metrics.flush()
  10. Prometheus Setup
  11. How It Works
  12. License

@elsbrock/cf-worker-otel

Push metrics from Cloudflare Workers to Prometheus, Grafana Cloud, or any OTLP-compatible backend — without pulling in the full OpenTelemetry SDK.

  • ~200 lines, zero runtime dependencies
  • Counters, gauges, and histograms
  • OTLP/HTTP JSON with delta temporality
  • Built for waitUntil() — never blocks your response
  • No-ops silently without config — safe to always instrument

Install

npm install @elsbrock/cf-worker-otel

Published to GitHub Packages. Add @elsbrock:registry=https://npm.pkg.github.com to your .npmrc.

Quick Start

import { createMetrics } from "@elsbrock/cf-worker-otel";

export default {
  async fetch(request, env, ctx) {
    const metrics = createMetrics({
      serviceName: "my-worker",
      endpoint: env.OTLP_ENDPOINT,
      token: env.OTLP_AUTH_TOKEN,
    });
    const start = Date.now();

    const response = await handleRequest(request);

    metrics.counter("http_requests_total", 1, {
      method: request.method,
      status: String(response.status),
    });
    metrics.histogram("http_request_duration_ms", Date.now() - start);

    ctx.waitUntil(metrics.flush());
    return response;
  },
};

SvelteKit on Cloudflare

// src/hooks.server.ts
import { createMetrics } from "@elsbrock/cf-worker-otel";
import { sequence } from "@sveltejs/kit/hooks";
import type { Handle } from "@sveltejs/kit";

const metricsHandle: Handle = async ({ event, resolve }) => {
  const env = event.platform?.env;
  const metrics = createMetrics({
    serviceName: "my-app",
    endpoint: env?.OTLP_ENDPOINT,
    token: env?.OTLP_AUTH_TOKEN,
  });
  const start = Date.now();
  let status = "500";
  try {
    const response = await resolve(event);
    status = String(response.status);
    return response;
  } finally {
    metrics.counter("http_requests_total", 1, {
      method: event.request.method,
      status,
      route: event.route.id ?? "unknown",
    });
    metrics.histogram("http_request_duration_ms", Date.now() - start);
    event.platform?.context?.waitUntil(metrics.flush());
  }
};

export const handle = sequence(metricsHandle, sessionHandle);

API

createMetrics(config)

Returns a per-request collector. Create one per invocation, flush at the end.

OptionTypeRequiredDescription
serviceNamestringyesMaps to service.name in OTLP
endpointstringnoOTLP HTTP endpoint URL
tokenstringnoBearer token for the Authorization header
defaultAttributesRecord<string, string>noMerged into every data point
histogramBoundsnumber[]noCustom bucket boundaries (default: HTTP latency in ms)

If endpoint or token is missing, flush() does nothing.

metrics.counter(name, value, attributes?)

Monotonic counter. Same name + same attributes are aggregated within the request.

metrics.gauge(name, value, attributes?)

Point-in-time value. Last write wins per attribute set.

metrics.histogram(name, value, attributes?)

Single observation placed into a bucket. Default bounds: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000] ms.

metrics.flush()

Serializes everything to OTLP JSON and POSTs it. Pass to ctx.waitUntil().

Prometheus Setup

Enable the OTLP receiver (v2.47+):

--web.enable-otlp-receiver

For delta temporality support (v3+):

--enable-feature=otlp-deltatocumulative

The receiver listens at POST /api/v1/otlp/v1/metrics on the Prometheus port.

How It Works

Each createMetrics() call creates an isolated collector. Metrics are accumulated in memory during request handling, then serialized to a single OTLP/HTTP JSON payload and POSTed in waitUntil(). One fetch per worker invocation — no batching across requests, no persistent state.

Delta temporality means each push contains only what happened in this request. Prometheus converts deltas to cumulative counters server-side.

License

MIT

版本与发布记录

@else42/cf-worker-otel 共发布 1 个版本,首次发布于 2026/04/05;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.2.2latest2026/04/057 个月前

关于 @else42/cf-worker-otel 的常见问题

@else42/cf-worker-otel 是什么?

Lightweight OTLP metrics client for Cloudflare Workers

如何安装 @else42/cf-worker-otel?

在项目目录运行 npm install @else42/cf-worker-otel,或使用 pnpm add / yarn add / bun add。

@else42/cf-worker-otel 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@else42/cf-worker-otel 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@else42/cf-worker-otel 可以商用吗?

@else42/cf-worker-otel 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@else42/cf-worker-otel 的下载量有多少?

根据 npm 官方下载统计,@else42/cf-worker-otel 在 2026/10/14 – 2026/11/12 这 30 天内被下载 2,360 次,日均约 79 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@else42/cf-worker-otel 还在维护吗?

最新版本 0.2.2 发布于 2026/04/05(7 个月前);至今共发布 1 个版本,其中过去 12 个月发布了 1 个;首次发布于 2026/04/05。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。