An OpenTelemetry compatible library for instrumenting and exporting traces for Cloudflare Workers
An OpenTelemetry compatible library for instrumenting and exporting traces for Cloudflare 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.
## 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.tomlfile.
compatibility_flags = [ "nodejs_compat" ]
…
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 }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:
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:
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()const exporter = {
url: 'https://api.honeycomb.io/v1/traces',
headers: { 'x-honeycomb-team': env.HONEYCOMB_API_KEY },
}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:
const fetchConf = (request: Request): boolean => {
return new URL(request.url).hostname === 'example.com'
}The handlers field of the configuration overrides the way in which event handlers, such as fetch or queue, are instrumented.
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:
const fetchConf = (request: Request): boolean => {
return new URL(request.url).hostname === 'example.com'
}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:
const postProcessor = (spans: ReadableSpan[]): ReadableSpan[] => {
spans[0].attributes['http.url'] = 'REDACTED'
return spans
}
…
typescript
const headSampler = new AlwaysOnSampler()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:
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 identifies the service and version to help with querying.
Example:
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.
}Register a custom propagator with:
const config: ResolveConfigFn = (env: Env, _trigger) => {
return {
propagator: new MyCoolPropagator(),
}
}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.
Triggers:
handler.email)handler.fetch)handler.queue)handler.scheduled)handler.tail)ctx.waitUntil)Globals/built-ins:
Cloudflare modules
cloudflare:emailcloudflare:socketsBindings:
No open issues yet, or sync has not completed.