posthogotel

package module
v1.44.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 19 Imported by: 0

README

PostHog OpenTelemetry bridge for AI observability

posthogotel forwards OpenTelemetry AI spans to PostHog AI observability.

It keeps only spans that follow a known AI semantic convention — a span whose name or any attribute key starts with gen_ai., llm., ai., or traceloop. — and drops every other span. Kept spans go over OTLP/HTTP to the PostHog /i/v0/ai/otel endpoint with the project API key as a bearer token.

This is a separate Go module, so the core posthog-go SDK does not depend on OpenTelemetry.

Usage

SpanProcessor is the recommended integration. Register it on the TracerProvider your application already owns — rather than replacing the global provider with a new one — so your resource, sampler, and existing exporters are kept and tracers already handed out (such as ADK Go's) route through it. Shut down the processor with a fresh context to flush its buffered spans without shutting down the application-owned provider.

If you don't already have a TracerProvider, create one and register the processor on it, as example/ does. Use WithHost for a host other than PostHog US cloud. For a framework that accepts only a span exporter, use NewExporter instead and pair it with your own batch span processor.

Per-request users and properties

import "github.com/posthog/posthog-go"

ctx = posthog.WithRequestContext(ctx, posthog.RequestContext{
    DistinctId: user.ID,
    Properties: posthog.Properties{"plan": "pro"},
})
// Pass this ctx to tracer.Start(ctx, ...) or to the instrumented SDK call, so
// the AI spans started from it are exported with the user and properties.
handleRequest(ctx)

An attribute already on the span wins over a property, and a property wins over the context's distinct ID and session ID. The context's session ID is added as $session_id, and the context's distinct ID is skipped when the span already has posthog.distinct_id, user.id, ai.telemetry.metadata.posthog_distinct_id or ai.settings.context.posthog_distinct_id. To set $ai_session_id, add it as a property or span attribute. The processor adds these attributes only to the AI spans it exports to PostHog. Other processors and exporters on the provider don't see them.

posthog.NewRequestContextMiddleware sets the request context from the PostHog tracing headers. It also adds request metadata ($current_url, $request_method, $request_path, $user_agent, $ip), and these are added to the AI spans exported to PostHog. To keep that metadata out, set the request context yourself with posthog.WithRequestContext instead of using the middleware.

Exception trace IDs

Use posthogotel.EnqueueWithContext to send a posthog.Exception with the active OpenTelemetry span's $trace_id and $span_id:

import (
    "github.com/posthog/posthog-go"
    posthogotel "github.com/posthog/posthog-go/otel"
)

err := posthogotel.EnqueueWithContext(ctx, client, posthog.Exception{
    DistinctId: "example-user",
    ExceptionList: []posthog.ExceptionItem{{
        Type: "ExampleError",
        Value: "Example failure",
    }},
})

Pass the context from the application operation that failed. The helper reads any valid active span, including spans that are not sampled. It does not require the AI span processor or export the span. IDs use lowercase hex with leading zeros.

Event properties override request-context properties, and both override derived trace IDs. Missing, invalid, or unreadable span context does not prevent exception capture. The helper copies properties, so reusing an exception does not keep IDs from a previous span. Other message types use the core enqueue behavior.

This is an explicit integration. client.Enqueue, posthog.EnqueueWithContext, and automatic panic capture do not read OpenTelemetry spans. The core SDK does not depend on OpenTelemetry.

Failed generations

PostHog decides that a generation failed from the OpenTelemetry span status, so set the status to the error code when a model call fails. Recording the error on the span is not enough on its own: in OpenTelemetry for Go that only adds an exception event and leaves the span status unset, so the failed generation reaches PostHog looking successful with an empty response. The Python and JavaScript instrumentation sets the status for you, which is why this step is specific to Go. Once the status is set, PostHog fills in the error message and HTTP status from the recorded exception event.

Google Agent Development Kit (ADK) for Go

ADK Go instruments its agents with OpenTelemetry and emits gen_ai.* spans on the global tracer provider. Register the PostHog span processor on that provider before you run the agent, and the agent's gen_ai.* spans reach PostHog with no further code.

Those spans carry the generation's model, token counts, latency, and finish reason. They do not carry prompt and response message content: ADK Go emits message bodies as OpenTelemetry log records (event names gen_ai.system.message, gen_ai.user.message, and gen_ai.choice), gated behind the OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT environment variable, not as span attributes. This bridge forwards spans only, so prompt and response fields stay empty for ADK Go generations.

See example/ for a runnable program.

General application spans

Register NewContextSpanProcessor(client) on your existing OpenTelemetry tracer provider to add sessionId and posthogDistinctId to application spans. A nil, disabled (empty API key), or closed client adds no IDs; a custom posthog.Client wrapper counts as enabled unless it implements IsEnabled() bool. Place it before processors that read attributes in OnStart. Keep your existing exporter and sampler.

Use posthogotel.NewRequestContextMiddleware(client, handler, options...) for HTTP requests. This wrapper uses the core SDK's header extraction and options. Place it inside the OpenTelemetry HTTP middleware so the request span already exists. It also works outside the OpenTelemetry middleware, because the processor reads context when that middleware starts the span. Pass r.Context() when you start child spans.

The bridge adds only missing IDs and preserves explicit span attributes. It does not create IDs or export spans. Register your normal application exporter to send general traces to PostHog. The AI SpanProcessor and Exporter above keep their separate AI-only behavior.

The HTTP wrapper stops new spans from using the request IDs after the handler returns or panics. Spans already started keep their IDs when they end later. Detached work that needs its own IDs must use a fresh context, such as context.Background() with posthog.WithFreshRequestContext. A context derived from an ended request remains expired.

For manual operations, posthog.WithRequestContext supplies IDs to the processor. The processor cannot determine when a manual operation ends. Use a new context for each operation and do not reuse its context for unrelated work.

OpenTelemetry remains optional through this separate module. This bridge adds no OpenTelemetry dependency to the core SDK. Non-recording spans and spans without readable public attributes receive no changes. Span attribute limits can omit new IDs while preserving existing attributes.

Documentation

Overview

Package posthogotel forwards OpenTelemetry AI spans to PostHog AI observability.

It keeps only spans that follow a known AI semantic convention. A span qualifies when its name or any of its attribute keys starts with one of "gen_ai.", "llm.", "ai.", or "traceloop.". Every other span is dropped. Kept spans go over OTLP/HTTP to the PostHog "/i/v0/ai/otel" endpoint with the project API key in an Authorization: Bearer header.

The package offers two integrations:

  • SpanProcessor is the recommended integration. It filters spans, batches the AI spans, and exports them. Register it with TracerProvider.RegisterSpanProcessor (or the WithSpanProcessor option). It also adds the PostHog request context (see posthog.WithRequestContext) to the AI spans it exports, which Exporter can't.

  • Exporter is for setups that supply their own span processor, or frameworks that accept only a span exporter. It filters spans and delegates the AI spans to an OTLP/HTTP exporter.

ContextSpanProcessor adds IDs to general application spans without exporting them. NewRequestContextMiddleware also enriches the existing incoming span and limits request IDs to the handler lifetime. These integrations use the application's provider and exporter, and add no IDs when the PostHog client is nil, disabled, or closed.

This is a separate Go module so that the core posthog-go SDK does not depend on OpenTelemetry. This module depends on the core module for the request context.

Index

Constants

View Source
const (
	// DefaultHost is the PostHog US cloud host used when WithHost is not set.
	DefaultHost = "https://us.i.posthog.com"
)

Variables

This section is empty.

Functions

func EnqueueWithContext added in v1.37.0

func EnqueueWithContext(ctx context.Context, client posthog.EnqueueClient, msg posthog.Message) error

EnqueueWithContext is the opt-in enqueue path for exceptions with OpenTelemetry trace IDs. It keeps event and request-context properties ahead of derived IDs. Other messages use posthog.EnqueueWithContext without trace enrichment.

func IsAISpan

func IsAISpan(span sdktrace.ReadOnlySpan) bool

IsAISpan reports whether a span follows a known AI semantic convention. It returns true when the span name, or any of its attribute keys, starts with one of the aiSpanPrefixes.

func NewRequestContextMiddleware added in v1.38.0

func NewRequestContextMiddleware(client posthog.Client, next http.Handler, opts ...posthog.RequestContextOption) http.Handler

NewRequestContextMiddleware also enriches the existing request span after header extraction. It adds IDs to spans only while client is enabled, like NewContextSpanProcessor. It accepts the core middleware options. Spans started from an inherited request context after the handler returns omit request IDs. Register ContextSpanProcessor for child spans.

Types

type ContextSpanProcessor added in v1.38.0

type ContextSpanProcessor struct {
	// contains filtered or unexported fields
}

ContextSpanProcessor adds PostHog IDs to spans from the application's provider. Register it before processors that consume attributes in OnStart. It does not export spans.

func NewContextSpanProcessor added in v1.38.0

func NewContextSpanProcessor(client posthog.Client) *ContextSpanProcessor

NewContextSpanProcessor creates an optional bridge for general application spans. It adds IDs only while client is enabled, so a nil, disabled, or closed client adds none. A client wrapper can implement IsEnabled() bool to report its state; otherwise it counts as enabled.

func (*ContextSpanProcessor) ForceFlush added in v1.38.0

func (*ContextSpanProcessor) OnEnd added in v1.38.0

func (*ContextSpanProcessor) OnStart added in v1.38.0

func (*ContextSpanProcessor) Shutdown added in v1.38.0

type Exporter

type Exporter struct {
	// contains filtered or unexported fields
}

Exporter is a span exporter that keeps only AI spans and forwards them to PostHog. Use it when you supply your own span processor, or with a framework that accepts only a span exporter. For most setups prefer SpanProcessor. Exporters only see finished spans, so they can't add PostHog request context; use SpanProcessor for that.

func NewExporter

func NewExporter(ctx context.Context, apiKey string, opts ...Option) (*Exporter, error)

NewExporter builds an Exporter for the given project API key.

func (*Exporter) ExportSpans

func (e *Exporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error

ExportSpans forwards the AI spans in the batch and drops the rest. It returns early without a request when the batch has no AI spans.

func (*Exporter) Shutdown

func (e *Exporter) Shutdown(ctx context.Context) error

Shutdown shuts down the underlying OTLP exporter.

type Option

type Option func(*config)

Option configures the exporter or the span processor.

func WithHost

func WithHost(host string) Option

WithHost sets the PostHog host, for example "https://eu.i.posthog.com". An empty or blank value keeps DefaultHost.

type SpanProcessor

type SpanProcessor struct {
	// contains filtered or unexported fields
}

SpanProcessor is a self-contained span processor that keeps only AI spans, batches them, and exports them to PostHog. Register it with TracerProvider.RegisterSpanProcessor or the sdktrace.WithSpanProcessor option. Spans started from a context carrying posthog.WithRequestContext are exported with its distinct ID, session ID and properties. Other processors on the provider don't see them.

func NewSpanProcessor

func NewSpanProcessor(ctx context.Context, apiKey string, opts ...Option) (*SpanProcessor, error)

NewSpanProcessor builds a SpanProcessor for the given project API key. It wraps a batch span processor around the PostHog OTLP exporter.

func (*SpanProcessor) ForceFlush

func (p *SpanProcessor) ForceFlush(ctx context.Context) error

ForceFlush flushes the pending AI spans through the batch span processor.

func (*SpanProcessor) OnEnd

func (p *SpanProcessor) OnEnd(s sdktrace.ReadOnlySpan)

OnEnd forwards AI spans to the batch processor and drops the rest. A forwarded span is a copy carrying the request context captured in OnStart.

func (*SpanProcessor) OnStart

func (p *SpanProcessor) OnStart(ctx context.Context, s sdktrace.ReadWriteSpan)

OnStart captures the PostHog request context carried by ctx (see posthog.WithRequestContext) for OnEnd. It never changes the live span.

func (*SpanProcessor) Shutdown

func (p *SpanProcessor) Shutdown(ctx context.Context) error

Shutdown shuts down the underlying batch span processor and releases the request contexts of spans that never ended.

Directories

Path Synopsis
Command example sends AI spans to PostHog AI observability through the posthogotel OpenTelemetry bridge.
Command example sends AI spans to PostHog AI observability through the posthogotel OpenTelemetry bridge.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址