Skip to content

Comments

Add Posthog Error Logging#32

Merged
iamEvanYT merged 2 commits intomainfrom
evan/posthog
May 3, 2025
Merged

Add Posthog Error Logging#32
iamEvanYT merged 2 commits intomainfrom
evan/posthog

Conversation

@iamEvanYT
Copy link
Member

@iamEvanYT iamEvanYT commented May 3, 2025

Summary by CodeRabbit

  • New Features
    • Integrated analytics and event tracking into the application, including automatic exception logging and anonymous user identification.
    • Application events and errors are now captured with additional metadata for improved insights.
  • Chores
    • Updated dependencies to include analytics support.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 3, 2025

Walkthrough

The changes introduce PostHog analytics integration into the application. The posthog-node dependency is added, a new module is created to initialize and manage the PostHog client, and event/error capture functions are provided. The module manages an anonymous user ID and enriches analytics events with application metadata. The main entry point imports this module to activate analytics on startup, and a listener ensures the analytics client is properly shut down before the application quits.

Changes

File(s) Change Summary
package.json Added posthog-node@^4.17.1 to dependencies.
src/main/index.ts Imported the new PostHog analytics module to initialize analytics on application startup.
src/main/modules/posthog.ts New module: Initializes PostHog client, manages anonymous user ID, exports captureEvent and captureException functions, captures "app-started" event, and handles client shutdown on app quit.

Sequence Diagram(s)

sequenceDiagram
    participant App as Electron App
    participant PosthogModule as PostHog Module
    participant PostHog as PostHog Service

    App->>PosthogModule: Import on startup
    PosthogModule->>PosthogModule: Initialize PostHog client
    PosthogModule->>PosthogModule: Retrieve or generate anonymous user ID
    PosthogModule->>PostHog: Capture "app-started" event

    Note over App,PosthogModule: During app lifecycle
    App->>PosthogModule: captureEvent / captureException
    PosthogModule->>PostHog: Send event or exception with metadata

    App->>PosthogModule: before-quit event
    PosthogModule->>PostHog: Shutdown client
Loading

Poem

In the code a new friend hops in,
PostHog tracks where journeys begin.
Events and errors, all in sight,
With anonymous paws, we log each byte.
When the app says goodbye,
Analytics waves hi—
A rabbit’s hop, with data to the sky! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/main/modules/posthog.ts (1)

1-53: 🛠️ Refactor suggestion

Add privacy notice for users

The code implements analytics tracking without a user-facing option to opt out. Consider adding a privacy setting to allow users to disable analytics collection.

Implement a privacy setting and conditional tracking:

import { SettingsDataStore } from "@/saving/settings";
import { app } from "electron";
import { PostHog } from "posthog-node";

const client = new PostHog("phc_P8uPRRW5eJj8vMmgMlsgoOmmeNZ9NxBHN6COZQndvfZ", {
  host: "https://eu.i.posthog.com",
  enableExceptionAutocapture: true
});

+async function isAnalyticsEnabled() {
+  const enabled = await SettingsDataStore.get<boolean>("analytics-enabled");
+  // Default to true if setting doesn't exist yet
+  return enabled === undefined ? true : enabled;
+}

async function getAnonUserId() {
  const anonUserId = await SettingsDataStore.get<string>("posthog-anon-id");
  if (!anonUserId) {
    const newAnonUserId = crypto.randomUUID();
    await SettingsDataStore.set("posthog-anon-id", newAnonUserId);
    return newAnonUserId;
  }
  return anonUserId;
}

function getAppInfoForPosthog() {
  return {
    version: app.getVersion(),
    platform: process.platform,
    environment: process.env.NODE_ENV
  };
}

export async function captureEvent(event: string, properties?: Record<string, unknown>) {
+  if (!(await isAnalyticsEnabled())) return;
  const anonUserId = await getAnonUserId();
  client.capture({
    distinctId: anonUserId,
    event: event,
    properties: {
      ...properties,
      ...getAppInfoForPosthog()
    }
  });
}

export async function captureException(error: Error, properties?: Record<string, unknown>) {
+  if (!(await isAnalyticsEnabled())) return;
  const anonUserId = await getAnonUserId();
  client.captureException(error, anonUserId, {
    ...properties,
    ...getAppInfoForPosthog()
  });
}

captureEvent("app-started");

app.on("before-quit", () => {
  client.shutdown();
});
🧹 Nitpick comments (1)
src/main/modules/posthog.ts (1)

48-48: Consider making the initial event more specific

The "app-started" event is triggered immediately on module import, but it would be more accurate to track after the app is fully initialized.

Consider moving this to the app's ready event:

-captureEvent("app-started");
+app.whenReady().then(() => {
+  captureEvent("app-initialized");
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b8909af and 74c9b57.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • package.json (1 hunks)
  • src/main/index.ts (1 hunks)
  • src/main/modules/posthog.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/main/modules/posthog.ts (1)
src/main/saving/settings.ts (1)
  • SettingsDataStore (7-7)
🔇 Additional comments (7)
package.json (1)

41-41: Added PostHog SDK dependency properly

The posthog-node package has been added with the correct version pattern using the caret ^ to allow backward compatible updates.

src/main/index.ts (1)

10-10: Properly integrated PostHog module

The PostHog module is imported efficiently using a side-effect import, which aligns with how other modules are imported in this file.

src/main/modules/posthog.ts (5)

10-18: Properly implemented anonymous user ID management

The implementation correctly persists and retrieves the anonymous user ID, ensuring consistent tracking across sessions while maintaining user privacy.


20-26: Good metadata collection for analytics

Collecting version, platform, and environment provides valuable context for analytics without exposing sensitive information.


28-38: Event capture implementation looks good

The captureEvent function properly handles asynchronous operations and enriches events with application metadata.


40-46: Exception capture implementation is correct

The captureException function correctly integrates with PostHog's error tracking capabilities while maintaining consistency with the event tracking approach.


50-52: Properly implemented PostHog client shutdown

The before-quit event handler ensures the PostHog client is shut down gracefully, preventing potential memory leaks or network issues during application exit.

@iamEvanYT iamEvanYT merged commit 6d99ff3 into main May 3, 2025
1 check passed
@iamEvanYT iamEvanYT deleted the evan/posthog branch May 3, 2025 17:09
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.

1 participant