Skip to content

Cloudflare

To instrument your Cloudflare Workers and send spans to Logfire, install the @pydantic/logfire-cf-workers and logfire NPM packages:

Terminal
npm install @pydantic/logfire-cf-workers logfire

Next, add the Node.js compatibility flag to your Wrangler configuration:

  • For wrangler.toml: compatibility_flags = [ "nodejs_compat" ]
  • For wrangler.jsonc: "compatibility_flags": ["nodejs_compat"]

Add your Logfire write token to your .dev.vars file:

Terminal
LOGFIRE_TOKEN=your-write-token
LOGFIRE_ENVIRONMENT=development

The LOGFIRE_ENVIRONMENT variable is optional and specifies the environment name for your service.

For production deployment, refer to the Cloudflare documentation on managing and deploying secrets. You can set secrets using the Wrangler CLI:

Terminal
npx wrangler secret put LOGFIRE_TOKEN

Finally, wrap your handler with the instrumentation. The instrument function will automatically configure Logfire using your environment variables:

import * as logfire from "logfire";
import { instrument } from "@pydantic/logfire-cf-workers";

const handler = {
  async fetch(): Promise<Response> {
    logfire.info("info span from inside the worker body");
    return new Response("hello world!");
  },
} satisfies ExportedHandler;

export default instrument(handler, {
  service: {
    name: "my-cloudflare-worker",
    namespace: "",
    version: "1.0.0",
  },
});

A complete working example is available in the examples/cf-worker directory.