Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
O

otel-cf-workers

> 编程语言
Open source

An OpenTelemetry compatible library for instrumenting and exporting traces for Cloudflare Workers

395 stars0 likes0 views
WebsiteGitHub

About

An OpenTelemetry compatible library for instrumenting and exporting traces for Cloudflare Workers

otel-cf-workers

An OpenTelemetry compatible library for instrumenting and exporting traces from Cloudflare Workers.

[!IMPORTANT] I have not been able to keep up with maintaining this library as much as I should have, but most importantly, a lot of the functionality in this package is now part of the Cloudflare Workers platform. You should always first try to use Workers Tracing — the OTEL tracing that is built into the Cloudflare Workers runtime, which automatically instruments your code and provides APIs to write custom spans, and export traces to external destinations, with or without persisting data to Cloudflare.

bash

## Getting started

```bash
npm install @microlabs/otel-cf-workers @opentelemetry/api

[!IMPORTANT] To be able to use the Open Telemetry library you have to add the NodeJS compatibility flag in your wrangler.toml file.

json
compatibility_flags = [ "nodejs_compat" ]

…

bash
typescript
import { trace } from '@opentelemetry/api'
import { instrument, ResolveConfigFn } from '@microlabs/otel-cf-workers'

export interface Env {
	HONEYCOMB_API_KEY: string
	OTEL_TEST: KVNamespace
}

const handler = {
	async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise {
		await fetch('https://cloudflare.com')

		const greeting = "G'day World"
		trace.getActiveSpan()?.setAttribute('greeting', greeting)
		ctx.waitUntil(fetch('https://workers.dev'))
		return new Response(`${greeting}!`)
	},
}

const config: ResolveConfigFn = (env: Env, _trigger) => {
	return {
		exporter: {
			url: 'https://api.honeycomb.io/v1/traces',
			headers: { 'x-honeycomb-team': env.HONEYCOMB_API_KEY },
		},
		service: { name: 'greetings' },
	}
}

export default instrument(handler, config)

…

typescript
import { instrumentDO, PartialTraceConfig } from '@microlabs/otel-cf-workers'

const config: ResolveConfigFn = (env: Env, _trigger) => {
	return {
		exporter: {
			url: 'https://api.honeycomb.io/v1/traces',
			headers: { 'x-honeycomb-team': env.HONEYCOMB_API_KEY },
		},
		service: { name: 'greetings-do' },
	}
}

class OtelDO implements DurableObject {
	async fetch(request: Request): Promise {
		return new Response('Hello World!')
	}
}

const TestOtelDO = instrumentDO(OtelDO, doConfig)

export { TestOtelDO }

Creating custom spans

While auto-instrumenting should take care of a lot of the information that you would want to add, there will always be application specific information you want to send along.

You can get the current active span by doing:

typescript
import {trace} from '@opentelemetry/api'

const handler = {
	async fetch(request: Request) {
		const span = trace.getActiveSpan()
		if(span) span.setAttributes('name', 'value')
		....
	}
}

Or if you want to create a new span:

typescript
import { trace } from '@opentelemetry/api'

const handler = {
	async fetch(request: Request) {
		const tracer = trace.getTracer('my_own_tracer_name')
		return tracer.startActiveSpan('name', (span) => {
			const response = await doSomethingAwesome
			span.end()
			return response
		})
	},
}

…

typescript
const exporter = new ConsoleSpanExporter()
typescript
const exporter = {
	url: 'https://api.honeycomb.io/v1/traces',
	headers: { 'x-honeycomb-team': env.HONEYCOMB_API_KEY },
}

Fetch

includeTraceContext is used to specify if outgoing requests should include the TraceContext so that the other service can participate in a distributed trace. The default is true for all outgoing requests, but you can turn it off for all requests with false, or specify a method that takes the outgoing Request method and return a boolean on whether to include the tracing context.

Example:

typescript
const fetchConf = (request: Request): boolean => {
	return new URL(request.url).hostname === 'example.com'
}

Handlers

The handlers field of the configuration overrides the way in which event handlers, such as fetch or queue, are instrumented.

Fetch Handler

acceptTraceContext is used to specify if incoming requests handled by fetch should accept a TraceContext and participate in a distributed trace. The default is true for all incoming requests, but you can turn it off for all requests with false or specify a method that takes the incoming Request and returns a boolean indicating whether to accept the tracing context.

Example:

typescript
const fetchConf = (request: Request): boolean => {
	return new URL(request.url).hostname === 'example.com'
}

PostProcessor

The PostProcessor function is called just before exporting the spans and allows you to make any changes to the spans before sending this. For example to remove entire spans, or to remove or redact security or privacy sensitive data.

Example:

typescript
const postProcessor = (spans: ReadableSpan[]): ReadableSpan[] => {
	spans[0].attributes['http.url'] = 'REDACTED'
	return spans
}

…

typescript
const headSampler = new AlwaysOnSampler()
typescript
const headSampler = {
	acceptRemote: false //Whether to accept incoming trace contexts
	ratio: 0.5 //number between 0 and 1 that represents the ratio of requests to sample. 0 is none and 1 is all requests.
}

Tail Sampling on the other hand is done at the end. Because we record every single span, even if it isn't head sampled, it is possible to still sample the local part of a trace in say the event of an error.

Example:

typescript
const tailSampler = (traceInfo: LocalTrace): boolean => {
	const localRootSpan = traceInfo.localRootSpan as unknown as ReadableSpan
	return (localRootSpan.spanContext().traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED
}

The default is a tailSampler that samples traces that have been head sampled or if the local root span is marked as an error.

Service

Service identifies the service and version to help with querying.

Example:

typescript
const service = {
	name: 'some_name' //required. The name of your service
	version: '1.0.4' //optional: An opaque version string. Can be a semver or git hash for example
	namespace: 'namespace' //optional: Useful to group multiple services together in one namespace.
}

Propagation

Register a custom propagator with:

typescript
const config: ResolveConfigFn = (env: Env, _trigger) => {
	return {
		propagator: new MyCoolPropagator(),
	}
}

Distributed Tracing

One of the advantages of using Open Telemetry is that it makes it easier to do distributed tracing through multiple different services. This library will automatically inject the W3C Trace Context headers when making calls to Durable Objects or outbound fetch calls.

Limitations

  • The worker runtime does not expose accurate timing information to protect against side-channel attacks such as Spectre and will only update the clock on IO, so any CPU heavy processing will look like it takes 0 milliseconds.
  • Not everything is auto-instrumented yet. See the lists below for what is and isn't.

Triggers:

  • Email (handler.email)
  • HTTP (handler.fetch)
  • Queue (handler.queue)
  • Cron (handler.scheduled)
  • Tail (handler.tail)
  • Durable Objects fetch
  • Durable Objects alarm
  • Durable Objects hibernated WebSocket
  • waitUntil (ctx.waitUntil)

Globals/built-ins:

  • Fetch
  • Caches
  • Durable Object Storage

Cloudflare modules

  • cloudflare:email
  • cloudflare:sockets

Bindings:

  • KV
  • Queue
  • Durable Objects
  • R2
  • D1
  • Service Bindings
  • Analytics Engine
  • Browser Rendering
  • Workers AI
  • Email Sending
  • mTLS
  • Vectorize
  • Hyperdrive
  • Workers for Platforms Dispatch

Issues· 43 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptcloudflareobservabilityotelworkers

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言