feat(otel): export traces to PostHog in production - #2360
Conversation
Mirrors the existing PostHog log export in the OpenTelemetry pipeline so spans land on the PostHog tracing page alongside logs and errors.
|
Bugbot is not enabled for your account, so this pull request was not reviewed. Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs. |
Reviewer's GuideAdds production-only PostHog OTLP trace exporting alongside existing Axiom exporting by introducing a span processor factory and wiring it into the OpenTelemetry NodeSDK, plus tests and a new PostHog traces URL constant. Sequence diagram for trace exporter setup in startInstrumentationsequenceDiagram
participant App
participant startInstrumentation
participant createSpanProcessors
participant NodeSDK
participant PostHogTracesEndpoint
App->>startInstrumentation: startInstrumentation(env)
startInstrumentation->>createSpanProcessors: createSpanProcessors(env)
createSpanProcessors-->>startInstrumentation: SpanProcessor[]
startInstrumentation->>NodeSDK: new NodeSDK({ spanProcessors })
alt hasPostHogTraceExport
startInstrumentation->>PostHogTracesEndpoint: OTLPTraceExporter url POSTHOG_TRACES_URL Authorization Bearer POSTHOG_API_KEY
end
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
LGTM! The addition of the PostHog trace exporter cleanly mirrors the existing log exporter pattern and includes thorough unit test coverage. 🤖 Reviewed by codereviewbot.ai - Catch bugs before your team does. |
PR Summary by QodoExport OpenTelemetry traces to PostHog in production
AI Description
Diagram
High-Level Assessment
Files changed (3)
|
|
Warning Review limit reached
Next review available in: 7 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe instrumentation now creates configurable Axiom and production PostHog trace processors. ChangesTrace exporting
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested labels: Suggested reviewers: Sequence Diagram(s)sequenceDiagram
participant startInstrumentation
participant createSpanProcessors
participant OpenTelemetrySDK
startInstrumentation->>createSpanProcessors: obtain configured processors
createSpanProcessors-->>startInstrumentation: return Axiom and/or PostHog processors
startInstrumentation->>OpenTelemetrySDK: pass complete processor list
🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Storybook previews for This comment updates automatically on each PR push. |
There was a problem hiding this comment.
Pull request overview
This PR extends the repository’s OpenTelemetry bootstrap (src/instrumentation.ts) to export traces to PostHog in production, mirroring the existing PostHog logs export path.
Changes:
- Add
POSTHOG_TRACES_URLconstant for PostHog’s OTLP traces endpoint. - Refactor span exporter setup into
createSpanProcessors()and enable PostHog trace export in production (while preserving any env-driven OTLP/Axiom export). - Add unit tests verifying PostHog trace exporter configuration and coexistence with an env-driven trace exporter.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| src/lib/posthog-config.ts | Adds POSTHOG_TRACES_URL constant for the PostHog OTLP traces endpoint. |
| src/instrumentation.ts | Introduces createSpanProcessors() and wires PostHog trace export in production alongside existing exporters. |
| src/instrumentation.test.ts | Adds unit tests covering PostHog trace exporter configuration and coexistence with an env-driven exporter. |
Suppressed comments (1)
src/instrumentation.test.ts:237
- Same brittleness here:
NodeSDK.mock.calls[0]can point at the module auto-start call if this test runs first/in isolation. Use the last call so this test is order-independent.
const config = vi.mocked(NodeSDK).mock.calls[0]?.[0];
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/instrumentation.test.ts`:
- Around line 208-240: Update the production PostHog exporter test around
startInstrumentation to run for both DEPLOY_ENVIRONMENT values, "prod" and
"production". Replace the partial OTLPTraceExporter assertions with exact
POSTHOG_TRACES_URL and Authorization values using the existing POSTHOG_API_KEY,
while preserving the Axiom coexistence test.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: e5f2fdcf-b30d-48a5-aebe-45e9050ac7d4
📒 Files selected for processing (3)
src/instrumentation.test.tssrc/instrumentation.tssrc/lib/posthog-config.ts
Code Review by Qodo
Context used✅ Compliance rules (platform):
144 rules✅ Skills:
fix-provider, write-tests, cloudflare 1. Prod tracing always-on
|
There was a problem hiding this comment.
2 issues found across 3 files
Confidence score: 3/5
src/instrumentation.tscan drop production tracing forcdc-healthandmetric-stream-clickhouse-sinkwhenDEPLOY_ENVIRONMENTis missing, which creates an observability blind spot in PostHog during incidents—setDEPLOY_ENVIRONMENTfor all instrumented prod services or derive the environment from deployment metadata.src/instrumentation.test.tsuses broadstringContainingchecks for the trace endpoint and auth header, so wrong PostHog hosts or malformed Bearer tokens could slip through CI and regress telemetry routing—tighten these to exact URL/header assertions.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/instrumentation.ts">
<violation number="1" location="src/instrumentation.ts:21">
P2: Production `cdc-health` and `metric-stream-clickhouse-sink` spans will not reach PostHog because these deployments omit `DEPLOY_ENVIRONMENT`. Set that variable for every instrumented production service, or derive the production condition from configuration shared by all production services.</violation>
</file>
<file name="src/instrumentation.test.ts">
<violation number="1" location="src/instrumentation.test.ts:219">
P3: The assertions here use `expect.stringContaining("/i/v1/traces")` and `expect.stringContaining("Bearer ")` instead of exact matches, so an incorrect PostHog host or malformed Authorization header would still pass. Additionally, only `DEPLOY_ENVIRONMENT: "production"` is exercised — `"prod"` (also treated as production by `isProductionDeployment`) isn't covered. Consider asserting the exact `POSTHOG_TRACES_URL` and `` `Bearer ${POSTHOG_API_KEY}` `` values and parameterizing the test for both `"prod"` and `"production"`.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
- Robustify NodeSDK config assertions (use last call, not first) so tests are order-independent against module auto-start. - Assert exact PostHog traces URL and bearer key in tests. - Parameterize production exporter test over both prod and production DEPLOY_ENVIRONMENT values. - Set DEPLOY_ENVIRONMENT for cdc-health and metric-stream-clickhouse-sink so all instrumented prod services export traces and logs to PostHog.
|
LGTM! The changes cleanly integrate PostHog trace exporting alongside Axiom, mirroring the existing log exporter structure. The updated unit tests appropriately verify both 🤖 Reviewed by codereviewbot.ai - Catch bugs before your team does. |
|
LGTM! The changes cleanly implement the PostHog trace exporter for production environments alongside Axiom trace exporting, with updated unit tests covering both 🤖 Reviewed by codereviewbot.ai - Catch bugs before your team does. |
There was a problem hiding this comment.
1 issue found across 4 files
Confidence score: 4/5
- In
deploy/stack.yml, settingDEPLOY_ENVIRONMENTforcdc-healthandmetric-stream-clickhouse-sinkcan unintentionally activate PostHog exporters via sharedcreateLogRecordProcessors/createSpanProcessorsinsrc/instrumentation.ts, which risks noisy telemetry or data being sent from services that weren’t meant to export it; verify intended environments and gate exporter activation explicitly for these services.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="deploy/stack.yml">
<violation number="1" location="deploy/stack.yml:184">
P2: This stack change sets `DEPLOY_ENVIRONMENT` on `cdc-health` and `metric-stream-clickhouse-sink`, which the shared `createLogRecordProcessors`/`createSpanProcessors` in `src/instrumentation.ts` use to enable PostHog exporters. The PR is described as adding PostHog *traces*, but because log export is keyed on the same `DEPLOY_ENVIRONMENT` flag and is not covered by the 10% trace sampler, these two services will also start sending their full logs to PostHog once they run instrumentation. That's a broader telemetry-egress change than the PR title suggests; worth confirming the intent (or scoping it to traces only) before merge.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Use the existing production runtime plus explicit OTLP trace setup for helper services, avoiding broader PostHog log export.
|
🤖 Review skipped: Repository rate limit exceeded. Free accounts are limited to 2 reviews per 4 hours per repository. Upgrade to a paid plan for unlimited reviews. |
|
Review-summary follow-up:
Validation: |
Summary
https://us.i.posthog.com/i/v1/tracesin production, mirroring the existing PostHog logs export (/i/v1/logs) insrc/instrumentation.ts.createSpanProcessors()keeps the Axiom trace export (env-driven) and adds aBatchSpanProcessorwith a Bearer-authOTLPTraceExporterto PostHog whenDEPLOY_ENVIRONMENTisprod/production. Auto-instrumentation is now active whenever PostHog traces are enabled too.phc_...) fromsrc/lib/posthog-config.ts, so no Infisical change is required.https://us.i.posthog.com/i/v1/traceswithAuthorization: Bearer <project API key>.Tests
/i/v1/tracesURL + Bearer header; Axiom and PostHog exporters coexist in production with an Axiom endpoint.pnpm test:unit(13,990 passed), root/server/webtsc --noEmit, andpnpm lint:sandboxall green. Fullpnpm lint'slint:analytics-sqlstep requires a running ClickHouse and was skipped locally (CI runs it).Notes
stack.ymldefaultsDEPLOY_ENVIRONMENT=production); spans will then appear on the PostHog tracing page.Summary by Sourcery
Enable OpenTelemetry span export to PostHog in production and wire it into the existing instrumentation setup alongside any Axiom exporters.
New Features:
Enhancements:
Tests:
Summary by cubic
Export OpenTelemetry traces to PostHog in production using a BatchSpanProcessor and OTLPTraceExporter with Bearer auth, so spans appear in PostHog. Reuses
POSTHOG_API_KEY; no new env vars.New Features
POSTHOG_TRACES_URL(https://us.i.posthog.com/i/v1/traces) withAuthorization: Bearer <POSTHOG_API_KEY>; enabled in prod even without Axiom endpoints.Bug Fixes
DEPLOY_ENVIRONMENT=prodorproductionas production; set it forcdc-healthandmetric-stream-clickhouse-sinkinstack.yml.NodeSDKcall for order-independence; clarify in-code docs on when instrumentation starts.Written for commit 96eb7f9. Summary will update on new commits.
Summary by CodeRabbit
New Features
Bug Fixes