SDKs overview

Cloudflare Trace leverages the OpenTelemetry project as its primary framework for instrumenting applications running on Cloudflare Workers. OpenTelemetry provides a set of APIs, SDKs, and tools designed to generate, collect, and export telemetry data (traces, metrics, and logs) from cloud-native software. By adopting this open standard, Cloudflare Trace offers developers a consistent way to add observability to their edge applications without proprietary vendor lock-in. The integration focuses on enabling distributed tracing for requests flowing through Workers, providing visibility into execution paths and performance characteristics. This approach allows for the use of standard OpenTelemetry libraries in JavaScript/TypeScript, which are then configured to send data to Cloudflare's observability backend.

The core benefit of this strategy is interoperability. Developers can use the same instrumentation code to send telemetry data to Cloudflare Trace or other OpenTelemetry-compatible analysis tools. Cloudflare provides specific guidance and examples on how to configure OpenTelemetry SDKs within the Workers environment to ensure proper data capture and transmission to the Trace service. This includes setting up exporters and context propagation mechanisms relevant to the serverless and edge computing paradigms. The SDKs enable the creation of spans, which represent individual operations within a trace, allowing for detailed performance analysis and debugging of complex request flows across multiple Workers or external services.

Official SDKs by language

Cloudflare Trace primarily supports instrumentation through the OpenTelemetry project's official SDKs, particularly for JavaScript/TypeScript environments relevant to Cloudflare Workers. While Cloudflare does not maintain proprietary SDKs specifically branded as "Cloudflare Trace SDKs," it provides clear documentation and examples for configuring standard OpenTelemetry libraries to work seamlessly with its tracing service. This approach ensures compatibility with a broad ecosystem of OpenTelemetry tools and integrations.

The following table outlines the key OpenTelemetry packages relevant for instrumenting Cloudflare Workers for use with Cloudflare Trace:

Language/Environment Key OpenTelemetry Package Maturity Description
JavaScript/TypeScript (Cloudflare Workers) @opentelemetry/sdk-trace-base Stable Provides the core tracing SDK for creating spans and managing trace context.
JavaScript/TypeScript (Cloudflare Workers) @opentelemetry/sdk-trace-web Stable Web-specific tracing SDK, adaptable for browser-like environments such as Workers.
JavaScript/TypeScript (Cloudflare Workers) @opentelemetry/api Stable Defines the OpenTelemetry API for interacting with the tracing system.
JavaScript/TypeScript (Cloudflare Workers) @opentelemetry/exporter-collector Stable Exports telemetry data to an OpenTelemetry Collector, which can then forward to Cloudflare Trace.
JavaScript/TypeScript (Cloudflare Workers) @opentelemetry/instrumentation-fetch Stable Provides automatic instrumentation for fetch requests, common in Workers.
JavaScript/TypeScript (Cloudflare Workers) @opentelemetry/instrumentation-http Stable Automatic instrumentation for HTTP/HTTPS modules, useful for Workers making internal or external requests.

Installation

To integrate OpenTelemetry with your Cloudflare Worker for tracing with Cloudflare Trace, you will typically install the necessary OpenTelemetry packages via npm. The installation process involves adding the core SDK, an exporter, and potentially specific instrumentation packages to your Worker project.

Prerequisites

  • Node.js and npm installed.
  • A Cloudflare Workers project initialized.

Steps for installation:

  1. Initialize your Worker project (if not already done):

    npx wrangler init my-worker
    cd my-worker
    
  2. Install core OpenTelemetry packages:

    Install the base tracing SDK, API, and an exporter. Cloudflare Trace typically expects data in the OpenTelemetry Protocol (OTLP) format, which can be sent via an OTLP exporter or an OpenTelemetry Collector.

    npm install @opentelemetry/api @opentelemetry/sdk-trace-base @opentelemetry/sdk-trace-web @opentelemetry/exporter-trace-otlp-proto
    

    The @opentelemetry/sdk-trace-web package is often used in Workers due to their JavaScript runtime environment. The @opentelemetry/exporter-trace-otlp-proto package directly exports traces using the OTLP protocol over HTTP, which is suitable for sending data to Cloudflare's observability backend or an OpenTelemetry Collector.

  3. Install instrumentation packages (optional but recommended):

    For automatic tracing of common operations like fetch requests, install relevant instrumentation packages:

    npm install @opentelemetry/instrumentation-fetch @opentelemetry/instrumentation-http
    
  4. Configure your Worker:

    After installation, you will need to configure the OpenTelemetry SDK within your Worker's code. This involves setting up a WebTracerProvider, registering the OTLP exporter, and enabling any desired instrumentations. Refer to the Cloudflare Trace OpenTelemetry guide for specific configuration details.

Quickstart example

This quickstart demonstrates how to set up basic OpenTelemetry tracing in a Cloudflare Worker to send traces to Cloudflare Trace. This example assumes you have installed the necessary OpenTelemetry packages as described in the Installation section.

First, ensure your wrangler.toml file is configured to allow outbound requests to your OpenTelemetry collector endpoint (e.g., Cloudflare Trace's ingest endpoint or a self-hosted collector).

In your Worker's src/index.ts or src/index.js file:

import { WebTracerProvider, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-web";
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
import { Resource } from "@opentelemetry/resources";
import { SemanticResourceAttributes } from "@opentelemetry/semantic-conventions";

// Configure the OTLP exporter to send data to Cloudflare Trace or a collector
const exporter = new OTLPTraceExporter({
  url: "YOUR_OTLP_COLLECTOR_ENDPOINT", // Replace with your actual endpoint
  headers: {},
});

// Create a TracerProvider
const provider = new WebTracerProvider({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: "my-cloudflare-worker",
  }),
});

// Register the exporter with a SimpleSpanProcessor
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

// Register the provider to activate tracing
provider.register();

// Register automatic instrumentations
registerInstrumentations({
  instrumentations: [
    new FetchInstrumentation({
      propagateTraceHeaderCorsUrls: [/.*/],
      ignoreUrls: [/YOUR_OTLP_COLLECTOR_ENDPOINT/],
    }),
  ],
});

// Worker event listener
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    // Get the tracer from the global API
    const tracer = provider.getTracer("my-worker-tracer");

    // Create a new span for the incoming request
    const span = tracer.startSpan("handleRequest");
    span.setAttribute("http.method", request.method);
    span.setAttribute("http.url", request.url);

    try {
      // Simulate some work or make an external fetch call
      await new Promise(resolve => setTimeout(resolve, 50));

      const response = new Response("Hello from Cloudflare Worker!");
      span.setAttribute("http.status_code", response.status);
      return response;
    } catch (error: any) {
      span.recordException(error);
      span.setStatus({ code: 2, message: error.message }); // 2 = ERROR
      return new Response(`Error: ${error.message}`, { status: 500 });
    } finally {
      // End the span when the request is complete
      span.end();
    }
  },
};

Note: Replace "YOUR_OTLP_COLLECTOR_ENDPOINT" with the actual endpoint provided by Cloudflare or your OpenTelemetry Collector. This endpoint is crucial for traces to reach Cloudflare Trace. For the most current and specific configuration, always refer to the official Cloudflare documentation for OpenTelemetry in Workers.

Community libraries

Given Cloudflare Trace's reliance on OpenTelemetry, community efforts primarily focus on extending OpenTelemetry's capabilities or providing utilities around its implementation within Cloudflare Workers. While there isn't a distinct ecosystem of "Cloudflare Trace community libraries" separate from OpenTelemetry, developers contribute to the broader OpenTelemetry community, which directly benefits Cloudflare Trace users. These contributions include:

  • Custom Instrumentations: Developers might create custom OpenTelemetry instrumentations for specific third-party libraries or internal services commonly used within Cloudflare Workers that are not yet covered by official OpenTelemetry packages. These can be shared as standalone npm packages.
  • Worker-specific Utilities: Community-made helper functions or wrappers that simplify the setup and configuration of OpenTelemetry within the unique Cloudflare Workers environment, such as managing context propagation in complex scenarios or integrating with other Workers features.
  • Examples and Boilerplates: Public repositories on platforms like GitHub often contain example Cloudflare Workers projects pre-configured with OpenTelemetry for tracing, serving as valuable resources for new users looking to implement observability.
  • OpenTelemetry Collector Configurations: Community members might share optimized configurations for the OpenTelemetry Collector specifically tailored for processing and forwarding Worker traces to various backends, including Cloudflare Trace.

To find such community resources, developers typically search for OpenTelemetry-related projects on GitHub, npm, or within Cloudflare's developer forums and Discord channels. The distributed nature of OpenTelemetry means that many general-purpose OpenTelemetry utilities and best practices are directly applicable to Cloudflare Trace users.