Generated banner for Instrument Tracing
Generated logo for Instrument Tracing

Instrument Tracing

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

Add PostHog distributed tracing to see how requests flow through services and where time goes. Use after implementing features or reviewing PRs to ensure request entry points, outbound calls, and background jobs produce spans, or when asked to add tracing or spans. Also handles pointing existing OpenTelemetry tracing at PostHog and initial OTLP exporter setup.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to implementing distributed tracing with PostHog. By leveraging the OpenTelemetry standard, it enables developers to track requests across services, databases, and background jobs. The process covers detection of the existing stack, configuration of OTLP exporters, and strategic placement of spans to identify performance bottlenecks and cross-service failures without requiring a proprietary PostHog SDK.

What it does

  • Analyzes existing codebase to detect language, framework, and current tracing setup.
  • Configures OpenTelemetry SDKs and OTLP HTTP exporters to send trace data to PostHog.
  • Implements auto-instrumentation for common frameworks and libraries.
  • Guides the manual addition of spans for background jobs and complex internal logic.
  • Links trace spans to specific users and sessions for enhanced observability.
  • Ensures proper flushing of trace data in serverless and short-lived environments.

When to use it

  • After implementing new features or reviewing pull requests to ensure proper observability.
  • When you need to diagnose latency issues or request flow problems across distributed services.
  • When tasked with adding tracing or spans to an existing application.
  • When migrating or pointing existing OpenTelemetry tracing configurations to PostHog.

Advantages

  • Uses industry-standard OpenTelemetry, avoiding vendor lock-in.
  • Provides deep visibility into request latency and service-to-service communication.
  • Supports a wide range of languages including Node.js, Python, Go, Java, .NET, PHP, and Ruby.
  • Enables correlation between backend traces and frontend user sessions.
  • Minimal impact on existing architecture through non-intrusive instrumentation.

Usage examples

“Add PostHog distributed tracing to my Python FastAPI application.”
The agent will analyze your project, install the necessary OpenTelemetry distro, configure the OTLP exporter to point to PostHog, and provide instructions for starting the app with the instrumentation wrapper.
“My Next.js app is slow. How can I see where the time is going?”
The agent will guide you through setting up OpenTelemetry in your Next.js project, specifically using the instrumentation.ts file to capture request entry points and outbound calls.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/posthog/instrument-tracing/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip instrument-tracing.zip -d .agents/skills

Documentation by PostHog

Add PostHog distributed tracing

Use this skill to add PostHog distributed tracing for new or changed code. Use it after implementing features or reviewing PRs to ensure request entry points, outbound calls, and background jobs produce spans, when the user asks to add tracing or spans, or to point existing OpenTelemetry tracing at PostHog. Supports any platform or language.

Supported platforms: Node.js, Next.js, Python (including Django, FastAPI, and Flask), Go, Java, .NET, PHP, Ruby, and any language via OpenTelemetry (OTLP).

PostHog tracing uses the standard OpenTelemetry SDK and an OTLP HTTP trace exporter. It does not need a PostHog SDK.

Instructions

Follow these steps IN ORDER:

STEP 1: Analyze the codebase and detect the platform.

  • Detect the language, framework, and existing tracing setup.

  • Look for dependency files and project files (package.json, requirements.txt, pyproject.toml, go.mod, pom.xml, build.gradle, *.csproj, Gemfile, composer.json, etc.).

  • Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, poetry.lock, uv.lock, go.sum, Gemfile.lock, composer.lock, etc.) to determine the package manager.

  • Look for existing tracing: an OpenTelemetry tracer provider, an instrumentation.ts file, an opentelemetry-instrument launch command, an OpenTelemetry Collector config, a Java agent flag, or another vendor's tracing agent.

  • Check whether a PostHog SDK (posthog-js, posthog-node, posthog-python) is already installed. You need this only for STEP 6.

STEP 2: Choose the capture path.

  • If the codebase already exports OpenTelemetry traces, point the existing OTLP trace exporter (or Collector) at PostHog. Reuse the existing tracer provider. If it exports to another tracing backend, ask the user before you add PostHog as a second destination.

  • Otherwise, add the OpenTelemetry SDK with an OTLP HTTP trace exporter and auto-instrumentation. Auto-instrumentation creates spans for HTTP servers, frameworks, and database drivers without code changes.

  • Read the platform reference that matches the detected stack now. Use its "With OpenTelemetry" section. If no reference matches, use the general installation reference.

STEP 3: Install dependencies. (Skip if the codebase already exports OpenTelemetry traces.)

  • Install the OpenTelemetry SDK, the OTLP HTTP/protobuf trace exporter, and the auto-instrumentation for the detected stack:

    • Node.js and Next.js: the packages from the platform reference, plus @opentelemetry/auto-instrumentations-node.

    • Python: opentelemetry-distro and opentelemetry-exporter-otlp-proto-http, then run opentelemetry-bootstrap -a install. It installs the instrumentation packages for the libraries the app already uses. Do not install opentelemetry-instrumentation-all.

    • Go: the packages from the platform reference, plus the contrib instrumentation for each library, such as go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.

    • Java: the zero-code opentelemetry-javaagent.jar. It needs no dependency changes.

    • .NET: OpenTelemetry, OpenTelemetry.Exporter.OpenTelemetryProtocol, and OpenTelemetry.Extensions.Hosting, plus OpenTelemetry.Instrumentation.AspNetCore and OpenTelemetry.Instrumentation.Http.

    • PHP: the packages from the platform reference. For auto-instrumentation, the opentelemetry PHP extension (from PECL) and the open-telemetry/opentelemetry-auto-* package for the framework, such as open-telemetry/opentelemetry-auto-slim.

    • Ruby: opentelemetry-sdk, opentelemetry-exporter-otlp, and opentelemetry-instrumentation-all, enabled with c.use_all.

  • Do not manually edit dependency files — use the package manager's install command.

STEP 4: Configure the OTLP trace exporter.

  • Send spans over OTLP HTTP/protobuf to /i/v1/traces on the PostHog host, with the project token in an Authorization: Bearer header. Do not use /i/v0/ai/otel. That endpoint accepts only LLM spans.

  • With environment variables, set the full path in OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and the header in OTEL_EXPORTER_OTLP_TRACES_HEADERS (Authorization=Bearer <token>). Do not set the base OTEL_EXPORTER_OTLP_ENDPOINT for PostHog. It appends its own /v1/traces path.

  • Set OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf where the SDK or agent defaults to gRPC. This applies to the Java agent, .NET, and Python with opentelemetry-distro.

  • Python with opentelemetry-distro: start the app with opentelemetry-instrument (for example, opentelemetry-instrument python app.py). It builds the tracer provider from the environment variables, so do not also build a provider in code. The distro also turns on OTLP metric and log export. Set OTEL_METRICS_EXPORTER=none and OTEL_LOGS_EXPORTER=none unless the app already sends those signals somewhere.

  • Set a service name (service.name, or OTEL_SERVICE_NAME) so spans are easy to find in the Tracing UI.

  • Start the provider before the application loads its frameworks, so auto-instrumentation can patch them. In Next.js, register the provider in instrumentation.ts behind the NEXT_RUNTIME === 'nodejs' check.

  • Follow the platform-specific reference for the exact configuration.

  • You must read a file immediately before attempting to write it.

STEP 5: Add spans where they belong.

  • Auto-instrumentation covers request entry points and most outbound calls. Add manual spans with the OpenTelemetry tracer API only where it has no coverage: background job handlers, queue consumers, and slow internal steps the user cares about.

  • Use low-cardinality span names like GET /users/:id, not GET /users/123. Put variable values in attributes.

  • Pass the W3C traceparent header on calls between services, so spans from each service join one trace.

  • Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.

STEP 6: Link spans to people and sessions. (Optional.)

  • A span joins a person and a Session Replay recording through the posthogDistinctId and sessionId span attributes.

  • If the app uses posthog-js, enable tracing_headers for your API hosts. The browser then sends X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers on each request.

  • With OpenTelemetry only, copy these values onto spans yourself. In the request handler or a middleware, read the two headers and set them as the posthogDistinctId and sessionId attributes on the active request span. Skip a header that is missing or empty.

  • If the app already uses the PostHog SDK, it can add these attributes for you. Do not install the PostHog SDK only for this step.

    • Python: add PostHogContextSpanProcessor from posthog.integrations.otel to the tracer provider. It copies the distinct ID and session ID from the active PostHog context onto each new span. Django's contexts middleware reads the headers and sets that context.

    • Node.js and Python: spans created with the PostHog SDK span API (posthog.withSpan, posthog.start_span) inside a PostHog request context get these attributes automatically. This needs posthog-node 5.52.0 or later, or posthog 7.58.0 or later, with the traces option set. These spans go through the PostHog SDK, not the OpenTelemetry provider. Use this only for apps that do not run OpenTelemetry.

STEP 7: Set up environment variables.

  • Check if the project already has PostHog environment variables configured (e.g. in .env, .env.local, or framework-specific env files). If valid values already exist, skip this step.

  • If the PostHog project token is missing, use the PostHog MCP server's projects-get tool to retrieve the project's api_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.

  • Use the project token (it starts with phc_). Do not use a personal API key (it starts with phx_).

  • For the PostHog host URL: check the projects-get MCP response for a region field — US maps to https://us.i.posthog.com, EU maps to https://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.

  • For the OTLP traces endpoint, use https://us.i.posthog.com/i/v1/traces (US) or https://eu.i.posthog.com/i/v1/traces (EU), matching the region determined above, with the project token as an Authorization: Bearer header.

  • Write these values to the appropriate env file using the framework's naming convention.

  • Reference these environment variables in code instead of hardcoding them.

STEP 8: Flush spans in short-lived processes.

  • The batch processor exports spans on an interval. A script, cron job, or serverless function can stop before the batch is sent.

  • On Vercel and other serverless platforms, call the provider's forceFlush() before the function returns. In Next.js 15.1 and later, call it inside after() from next/server.

  • On AWS Lambda, call forceFlush() at the end of each invocation. Do not call shutdown() there, because the runtime reuses the container. Call shutdown() only when the process exits.

STEP 9: Verify spans arrive.

  • Run the application and trigger the instrumented code.

  • Open Tracing in the PostHog sidebar and filter by the service name. Spans should appear within a minute of sending.

  • If no spans appear, check the endpoint path, the Bearer token, the exporter protocol, and the flush step.

Reference files

  • references/nodejs.md - Node.js tracing installation

  • references/nextjs.md - Next.js tracing installation

  • references/python.md - Python tracing installation

  • references/go.md - Go tracing installation

  • references/java.md - Java tracing installation

  • references/dotnet.md - .net tracing installation

  • references/php.md - Php tracing installation

  • references/ruby.md - Ruby tracing installation

  • references/installation.md - Install tracing

  • references/start-here.md - Getting started with distributed tracing

  • references/basics.md - Why you need distributed tracing

  • references/COMMANDMENTS.md - Framework-specific rules the integration must follow

Each platform reference contains specific OpenTelemetry setup, OTLP configuration, and integration patterns. Find the one matching the user's stack.

Key principles

  • OpenTelemetry first: PostHog traces use the OpenTelemetry protocol. Use the OpenTelemetry SDK with auto-instrumentation, and reuse an existing tracer provider when there is one. The PostHog SDK is optional.

  • Environment variables: Always use environment variables for PostHog keys and OpenTelemetry endpoints. Never hardcode them.

  • Minimal changes: Add PostHog trace export alongside existing code. Don't replace or restructure existing tracing.

  • Boundaries, not every function: A few spans at request entry, outbound calls, and background jobs are better than a span around every function.

  • No secrets in attributes: Never put tokens, passwords, or other secrets in span names or attributes.

Files

references/python.md

AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt

Python tracing installation

Canonical URL: https://posthog.com/docs/distributed-tracing/installation/python

Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use https://eu.i.posthog.com instead of https://us.i.posthog.com (ingestion host), and use https://eu.posthog.com instead of https://app.posthog.com (app host for links).

On this page

  • With posthog

  • With OpenTelemetry

  • Test your setup

  • Next steps

There are two ways to send spans from Python.

posthogOpenTelemetry
PackagesThe SDK you already use for analyticsopentelemetry-sdk and an OTLP exporter
InstrumentationManual – you wrap the operations you care aboutManual, plus auto-instrumentation for Django, Flask, FastAPI, databases, and more
Person and session joinAutomatic inside a PostHog context that identifies themOptional PostHog context processor

Pick OpenTelemetry if you already run it, if you use asyncio with AsyncPosthog, or if you want spans from your web framework and database driver without writing them yourself. Pick posthog if PostHog is your only tracing backend and you'd rather instrument a handful of operations by hand than add an exporter pipeline.

Both routes send OTLP spans to the same endpoint, so you can start with one and switch later without losing your traces.

With posthog

Minimum version: posthog 7.58.0 or later.

  1. 1

    Install posthog

    Required

    pip install "posthog>=7.58.0"
  2. 2

    Enable tracing

    Required

    Tracing is off until you set the traces option. There's no OpenTelemetry dependency to add.

    from posthog import Posthog
    
    posthog = Posthog(
        "<ph_project_token>",
        host="https://us.i.posthog.com",
        traces={
            "service_name": "checkout-api",
            "environment": "production",
        },
    )
    OptionDescription
    service_nameIdentifies the service in the Tracing UI. Maps to service.name
    service_versionRelease version. Maps to service.version
    environmentDeployment environment, e.g. production. Maps to deployment.environment
    resource_attributesAdditional OpenTelemetry resource attributes

    Use your project token (the same one you use for capturing events), not a personal API key. Tracing works with the synchronous Posthog client and the module-level API, not AsyncPosthog.

    See the Python SDK docs for batching, queue, and span-limit options, and before_span_send for scrubbing attributes or dropping spans before they're exported.

  3. 3

    Create spans with posthog

    Required

    start_span used in a with block makes the span active for the block and ends it when the block exits. Spans started inside the block nest underneath it automatically.

    with posthog.start_span("POST /checkout", kind="server") as span:
        span.set_attribute("plan", user.plan)
    
        with posthog.start_span("create-order"):
            order = create_order(cart)
        with posthog.start_span("charge-card"):
            stripe.charge(order)

    If an exception escapes the block, the span records it, its status is set to error, and the exception propagates unchanged.

    Span names should be low-cardinality operation names – GET /users/:id, not GET /users/123. Variable values belong in attributes.

    For work that can't wrap a block, call start_span without with and call end() yourself. See the Python SDK docs for the full span API and for continuing a trace across services with W3C traceparent headers.

  4. 4

    Recommended

    Spans created inside a PostHog context that has a distinct ID or session ID carry posthogDistinctId and sessionId attributes, which is what makes a trace reachable from a person or a Session Replay recording.

    from posthog import new_context, identify_context, set_context_session
    
    with new_context():
        identify_context(user.id)
        set_context_session(session_id)
    
        with posthog.start_span("POST /checkout"):
            process_order()

    If you use Django, the contexts middleware sets this up for every request, and reads the X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers that tracing_headers sends from the browser.

  5. 5

    Flush before the process exits

    Recommended

    Queued spans are exported on an interval, even with sync_mode on, so a short-lived process can exit before they're sent. Both flush() and shutdown() export spans that have already ended.

    def handler(event, context):
        with posthog.start_span("handler"):
            do_work()
        posthog.flush()

    In a serverless handler, call flush() before returning. Call shutdown() when the process is genuinely exiting.

With OpenTelemetry

  1. 1

    Install OpenTelemetry packages

    Required

    For the complete SDK reference, see the OpenTelemetry Python docs.

    pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http

    opentelemetry-exporter-otlp-proto-http is the OTLP HTTP/protobuf trace exporter. The -proto-grpc variant sends gRPC, so pick -proto-http to match this guide.

  2. 2

    Get your project token

    Required

    You'll need your PostHog project token to authenticate trace requests. This is the same token you use for capturing events with the PostHog SDK.

    Important: Use your project token which starts with phc_. Do not use a personal API key (which starts with phx_).

    You can find your project token in Project settings.

  3. 3

    Configure the SDK

    Required

    Set up the OpenTelemetry SDK to export spans to PostHog over OTLP HTTP.

    from opentelemetry import trace
    from opentelemetry.sdk.resources import Resource, SERVICE_NAME
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
    
    resource = Resource.create({SERVICE_NAME: "my-service"})
    provider = TracerProvider(resource=resource)
    
    exporter = OTLPSpanExporter(
        endpoint="https://us.i.posthog.com/i/v1/traces",
        headers={"Authorization": "Bearer <ph_project_token>"},
    )
    
    provider.add_span_processor(BatchSpanProcessor(exporter))
    trace.set_tracer_provider(provider)

    The .http. segment in the import path is what selects the HTTP/protobuf exporter.

    Alternatively, configure the exporter with environment variables:

    OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="https://us.i.posthog.com/i/v1/traces"
    OTEL_EXPORTER_OTLP_TRACES_HEADERS="Authorization=Bearer <ph_project_token>"
    OTEL_SERVICE_NAME="my-service"

    Note: Pass the full /i/v1/traces path to the traces endpoint. Don't use the base OTEL_EXPORTER_OTLP_ENDPOINT variable, which appends its own /v1/traces.

  4. 4

    Create spans

    Required

    Wrap the operations you want to measure in spans, and attach attributes for context.

    tracer = trace.get_tracer("my-service")
    
    def checkout(order_id, amount):
        with tracer.start_as_current_span("checkout") as span:
            span.set_attribute("order.id", order_id)
            span.set_attribute("order.amount", amount)
            # ... do work ...
            return "confirmed"

    To link spans to people and sessions, add the optional PostHog context processor to your existing provider before requests start:

    from posthog.integrations.otel import PostHogContextSpanProcessor
    
    provider.add_span_processor(PostHogContextSpanProcessor())

    Keep your existing provider, exporter, and sampler. This integration supports OpenTelemetry SDK 1.20.0 or later. The processor adds missing posthogDistinctId and sessionId attributes from the active PostHog context when each span starts. Explicit attributes take precedence. If the span has too little attribute capacity, enrichment is skipped to preserve its existing attributes.

    The PostHog Django, Flask, and ASGI integrations also enrich an active request span after they read the request context. Put the OpenTelemetry request middleware outside the PostHog middleware. Configure tracing_headers in the browser SDK. The PostHog framework integrations capture these headers by default with Python SDK 7.71.0 or later. Set capture_tracing_headers=False, or POSTHOG_MW_CAPTURE_TRACING_HEADERS = False in Django, to disable extraction. These headers are untrusted analytics context.

    For Celery, initialize the PostHog Celery integration before OpenTelemetry Celery instrumentation. This order also preserves task context for eager or nested execution.

    For a custom integration, call enrich_current_span() from posthog.integrations.otel after you set the request IDs. The processor handles child spans started later in that context.

    Missing IDs stay absent. Spans that already started keep their attributes after the context ends. New spans in detached tasks do not receive the ended context's IDs. Set explicit IDs in a new new_context() scope for background work. The bridge does not transfer context to another process or thread. Error-response spans created outside the PostHog middleware scope, including outer FastAPI error handling, can omit request IDs.

  5. Test your setup

    Checkpoint

    Confirm spans are reaching PostHog

    Whichever route you took:

    1. Run your application and trigger the instrumented code

    2. Open the PostHog Tracing interface

    3. Confirm your spans and traces appear

    View your traces in PostHog

  6. Next steps

    Checkpoint

    What you can do with your traces

    ActionDescription
    Why you need distributed tracingWhat a trace shows you that nothing else does
    Explore tracesRead a trace as a waterfall to see where time goes
    Filter spansNarrow down by service, status, duration, and attributes
    Propagate contextPass trace context across services so spans join the same trace

    View your traces in PostHog

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs an API key, Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/omnibus/instrument-tracing · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by PostHog or PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-tracing.zip