Skip to content

feat(observability): forward Winston error logs to PostHog Error Tracking (closes #3651)#3654

Merged
PierreBrisorgueil merged 4 commits into
masterfrom
winston-posthog-transport
May 11, 2026
Merged

feat(observability): forward Winston error logs to PostHog Error Tracking (closes #3651)#3654
PierreBrisorgueil merged 4 commits into
masterfrom
winston-posthog-transport

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

Summary

  • Adds PostHogErrorTransport — a custom Winston transport that forwards error-level (and above) logs to PostHog Error Tracking via the existing errorTracker.captureException() service.
  • Wires the transport in logger.js conditionally on config.analytics.posthog.errorTracking === true (opt-in, no change for unconfigured projects).
  • Marks err.posthogCaptured = true in errorTracker.setupExpressErrorHandler after Express captures an error, so the same exception is never double-sent to PostHog by the Winston transport.

Closes #3651

Changes

File Change
lib/services/logger.posthog.transport.js NEW — PostHogErrorTransport class
lib/services/logger.js Wire transport when errorTracking=true
lib/services/errorTracker.js Mark err.posthogCaptured = true after Express capture
lib/services/tests/logger.posthog.transport.unit.tests.js 7 unit tests (TDD)
lib/services/tests/logger.posthog.transport.wiring.unit.tests.js 2 wiring tests
lib/services/tests/logger.posthog.transport.integration.tests.js 3 integration tests
lib/services/tests/errorTracker.unit.tests.js +1 dedup flag test

Dedup design

logger.error(err)  ─────┐
                         ▼
             PostHogErrorTransport.log()
               └─ err.posthogCaptured? → skip
               └─ errorTracker.captureException()
               └─ sourceErr.posthogCaptured = true

Express error middleware
  └─ errorTracker.captureException()
  └─ err.posthogCaptured = true   ← dedup flag

When an unhandled error bubbles through Express AND was previously logged via logger.error, the middleware marks the flag so the transport skips it on the second pass.

Notes from pre-push critical-review

  • Unconditional ESM import: logger.posthog.transport.js is always imported at module-load time (ESM static imports) even when errorTracking=false. Functionally safe — errorTracker guards its own config check. Can be lazy-loaded via dynamic import() in a follow-up if module-load budget becomes a concern.
  • Wiring test mock: The plan's mock config didn't include log.fileLogger — added to prevent getLogOptions() crash in test isolation. Behavior under test is unchanged.

Test plan

  • 7 unit tests for PostHogErrorTransport (level default, Error forwarding, info.error extraction, synthetic Error wrapping, dedup skip, posthogCaptured flag set, SDK throw safety)
  • 2 wiring tests (transport registered when errorTracking=true, absent when false)
  • 3 integration tests (message+error, bare Error, already-captured skip)
  • 1 errorTracker dedup flag test
  • npm run lint — clean
  • npm run test:unit — 1379 passed
  • npm run test:coverage — thresholds unchanged

Related

Copilot AI review requested due to automatic review settings May 11, 2026 09:20
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 11, 2026

Warning

Rate limit exceeded

@PierreBrisorgueil has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 39 minutes and 45 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 82025ccd-d769-4dfb-9e17-7d92d39943d9

📥 Commits

Reviewing files that changed from the base of the PR and between 48766e5 and 3603807.

📒 Files selected for processing (7)
  • lib/services/errorTracker.js
  • lib/services/logger.js
  • lib/services/logger.posthog.transport.js
  • lib/services/tests/errorTracker.unit.tests.js
  • lib/services/tests/logger.posthog.transport.integration.tests.js
  • lib/services/tests/logger.posthog.transport.unit.tests.js
  • lib/services/tests/logger.posthog.transport.wiring.unit.tests.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch winston-posthog-transport

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 11, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.20%. Comparing base (48766e5) to head (3603807).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3654      +/-   ##
==========================================
+ Coverage   89.15%   89.20%   +0.05%     
==========================================
  Files         135      136       +1     
  Lines        4646     4668      +22     
  Branches     1437     1451      +14     
==========================================
+ Hits         4142     4164      +22     
  Misses        392      392              
  Partials      112      112              
Flag Coverage Δ
integration 59.59% <86.36%> (+0.51%) ⬆️
unit 64.35% <100.00%> (+0.16%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 48766e5...3603807. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@PierreBrisorgueil PierreBrisorgueil merged commit a91b07b into master May 11, 2026
9 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the winston-posthog-transport branch May 11, 2026 09:22
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds opt-in forwarding of Winston error (and above) logs to PostHog Error Tracking, integrating with the existing errorTracker.captureException() path and introducing a dedup flag to avoid double-sending the same Error object.

Changes:

  • Introduces PostHogErrorTransport (custom Winston transport) to forward error logs to PostHog via errorTracker.captureException().
  • Conditionally wires the transport into the global logger when config.analytics.posthog.errorTracking === true.
  • Marks err.posthogCaptured = true in the Express error middleware path and adds unit/wiring/integration tests around the new behavior.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
lib/services/logger.posthog.transport.js New Winston transport that forwards error logs to PostHog and attempts dedup via err.posthogCaptured.
lib/services/logger.js Conditionally registers the PostHog transport when error tracking is enabled.
lib/services/errorTracker.js Marks errors with posthogCaptured in the Express error handler for deduplication.
lib/services/tests/logger.posthog.transport.unit.tests.js Unit coverage for transport extraction/wrapping, dedup skip, and “never throw” behavior.
lib/services/tests/logger.posthog.transport.wiring.unit.tests.js Verifies conditional transport registration based on config.
lib/services/tests/logger.posthog.transport.integration.tests.js End-to-end verification that logger.error(...) produces $exception events and respects the dedup flag.
lib/services/tests/errorTracker.unit.tests.js Adds a test asserting the dedup flag is set by the Express error handler.

Comment on lines 54 to 56
captureException(err, { distinctId, requestId: req.id });
if (err && typeof err === 'object') err.posthogCaptured = true;
next(err);
Comment on lines +17 to +21
export class PostHogErrorTransport extends Transport {
constructor(opts = {}) {
super({ ...opts, level: opts.level ?? 'error' });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(observability): forward Winston error-level logs to PostHog Error Tracking via custom transport

2 participants