AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

instrument-error-tracking

Add PostHog error tracking to capture and monitor exceptions. Use after implementing features or reviewing PRs to ensure errors are tracked with stack traces and source maps. Also handles initial PostHog SDK setup if not yet installed.

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--instrument-error-tracking at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 30

references/go.md

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

Go Error Tracking installation

Canonical URL: https://posthog.com/docs/error-tracking/installation/go

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

Install with the wizard

Run this command in your project directory to add PostHog to your Go project. The wizard detects your framework, installs the SDK, and sets up your first events.

npx @posthog/wizard

Or set it up manually by following the rest of this guide.

  1. 1

    Install the Go SDK

    Required

    Install the PostHog Go SDK:

    go get github.com/posthog/posthog-go
    

    Debug symbol uploads

    The Go SDK resolves stack traces in-process, so captured frames include file names, line numbers, function names, and inlined calls without any symbol uploads. To also see source context (the surrounding lines of code in the error tracking UI), upload debug symbols. That needs posthog-go 1.22.0 or later.

  2. 2

    Initialize the client

    Required

    package main
    
    import (
        "github.com/posthog/posthog-go"
    )
    
    func main() {
        client, _ := posthog.NewWithConfig(
            "<ph_project_token>",
            posthog.Config{
                Endpoint: "https://us.i.posthog.com",
            },
        )
        defer client.Close()
    }
    
  3. 3

    Capture exceptions

    Required

    There are two ways to capture exceptions with the Go SDK:

    Option A: Direct capture

    Use NewDefaultException to capture errors directly. This automatically generates a UUID and stack trace for you.

    import (
        "time"
        "github.com/posthog/posthog-go"
    )
    
    exception := posthog.NewDefaultException(
        time.Now(),
        "user_distinct_id",
        "DatabaseError",         // type - rendered as title in the UI
        "connection refused",    // value - rendered as description in the UI
    )
    client.Enqueue(exception)
    

    For more control, build the Exception struct manually:

    import (
        "time"
        "github.com/posthog/posthog-go"
    )
    
    handled := true
    fingerprint := "my-custom-fingerprint"
    
    exception := posthog.Exception{
        DistinctId: "user_distinct_id",
        Timestamp:  time.Now(),
        ExceptionList: []posthog.ExceptionItem{
            {
                Type:  "DatabaseError",
                Value: "connection refused",
                Mechanism: &posthog.ExceptionMechanism{
                    Handled: &handled,
                },
            },
        },
        ExceptionFingerprint: &fingerprint,
    }
    client.Enqueue(exception)
    

    To see how net/http services can automatically associate backend exceptions with frontend users, view the Go request context documentation.

    Option B: Automatic capture with slog

    The SDK provides a SlogCaptureHandler that wraps Go's standard log/slog logger and automatically captures log records as exceptions.

    By default, it captures logs at Warning level and above.

    import (
        "context"
        "fmt"
        "log/slog"
        "os"
    
        "github.com/posthog/posthog-go"
    )
    
    client, _ := posthog.NewWithConfig(
        "<ph_project_token>",
        posthog.Config{
            Endpoint: "https://us.i.posthog.com",
        },
    )
    defer client.Close()
    
    baseHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
        Level: slog.LevelInfo,
    })
    
    logger := slog.New(posthog.NewSlogCaptureHandler(baseHandler, client,
        posthog.WithDistinctIDFn(func(ctx context.Context, r slog.Record) string {
            // Return the user ID from context or another source
            return "user_distinct_id"
        }),
    ))
    
    // This warning is automatically captured as an exception in PostHog
    logger.Warn("Something broke",
        "error", fmt.Errorf("connection refused"),
    )
    

    The handler supports several configuration options:

    | Option | Description | Default | | --- | --- | --- | | WithMinCaptureLevel(level) | Minimum log level to capture | slog.LevelWarn | | WithDistinctIDFn(fn) | Function to extract distinct ID from context/record | Returns "" (skips capture) | | WithFingerprintFn(fn) | Custom fingerprint for error grouping | nil (PostHog assigns) | | WithSkip(n) | Stack frames to skip | 5 | | WithStackTraceExtractor(e) | Custom stack trace extractor | DefaultStackTraceExtractor | | WithDescriptionExtractor(e) | Custom description extractor | ErrorExtractor |

    Error extraction

    The slog handler automatically extracts error descriptions from log attributes with keys err or error (case-insensitive). It also supports wrapped errors via the Unwrap() interface.

  4. 4

    Verify error tracking

    Recommended

    Trigger a test exception to confirm events are being sent to PostHog. You should see them appear in the activity feed.

    exception := posthog.NewDefaultException(
        time.Now(),
        "test_user",
        "TestError",
        "This is a test exception from Go",
    )
    client.Enqueue(exception)
    
    // Flush the queue before exiting
    client.Close()