Golang Observability
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Tool integration
- Cloud and DevOps
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a standardized approach to instrumenting Go applications for production monitoring. It covers the five essential signals—logs, metrics, traces, profiles, and real-user monitoring—to ensure full system visibility. It emphasizes best practices such as structured logging with slog, histogram-based latency tracking, context propagation for distributed tracing, and proactive alerting. The skill includes guidance on migrating legacy loggers, correlating signals for easier debugging, and ensuring features are production-ready through rigorous observability standards.
What it does
- Provides best practices for structured logging using log/slog.
- Guides the implementation of Prometheus metrics and OpenTelemetry tracing.
- Offers strategies for continuous profiling and real-user monitoring.
- Details how to correlate logs, metrics, and traces for effective diagnostics.
- Includes a checklist for ensuring features meet production observability standards.
- Provides guidance on migrating from legacy logging libraries to the standard library.
When to use it
- When instrumenting new Go services for production monitoring.
- When adding observability to existing features or refactoring legacy code.
- When setting up alerting rules or Grafana dashboards for Go applications.
- When migrating legacy loggers like zap or logrus to the standard log/slog library.
- When implementing GDPR/CCPA-compliant event tracking.
Advantages
- Promotes consistent observability patterns across Go codebases.
- Reduces technical debt by standardizing on Go's native logging and instrumentation.
- Improves incident response times through better signal correlation.
- Ensures production readiness by enforcing observability as a definition of done.
- Provides clear guidance on avoiding common pitfalls like high-cardinality labels.
Usage examples
- “How should I instrument a new HTTP endpoint in my Go service for observability?”
- The agent will guide you to add structured logging with slog, declare Prometheus metrics for latency and error rates, and create OpenTelemetry spans for the request flow.
- “Help me migrate my project from zap to log/slog.”
- The agent will provide a step-by-step migration strategy, including using bridge handlers to maintain compatibility while gradually replacing log calls.
- “How do I link my logs to my traces in Go?”
- The agent will show you how to use the otelslog bridge to automatically inject trace_id and span_id into your logs using context.
- “What is the best way to track latency for my API endpoints?”
- The agent will recommend using Prometheus Histograms instead of Summaries to allow for server-side aggregation and accurate percentile calculation.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/samber/golang-observability/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-observability.zip -d .agents/skills
Documentation by samber
Persona: You are a Go observability engineer. You treat every unobserved production system as a liability — instrument proactively, correlate signals to diagnose, and never consider a feature done until it is observable.
Orchestration mode: Fan out the five signal-specific sub-agents described in Audit mode (metrics, logging, tracing, profiling, RUM) for auditing observability coverage across a codebase, and merge their coverage findings. On Claude Code, use ultracode to opt into multi-agent orchestration explicitly.
Modes:
Coding / instrumentation (default): Add observability to new or existing code — declare metrics, add spans, set up structured logging, wire pprof toggles. Follow the sequential instrumentation guide.
Review mode — reviewing a PR's instrumentation changes. Check that new code exports the expected signals (metrics declared, spans opened and closed, structured log fields consistent). Sequential.
Audit mode — auditing existing observability coverage across a codebase. Launch up to 5 parallel sub-agents — one per signal (metrics, logging, tracing, profiling, RUM) — to check coverage simultaneously.
Community default. A company skill that explicitly supersedes
samber/cc-skills-golang@golang-observabilityskill takes precedence.
Go Observability Best Practices
Observability is the ability to understand a system's internal state from its external outputs. In Go services, this means five complementary signals: logs, metrics, traces, profiles, and RUM. Each answers different questions, and together they give you full visibility into both system behavior and user experience.
When using observability libraries (Prometheus client, OpenTelemetry SDK, vendor integrations), refer to the library's official documentation and code examples for current API signatures.
Best Practices Summary
Use structured logging with
log/slog— production services MUST emit structured logs (JSON), not freeform stringsChoose the right log level — Debug for development, Info for normal operations, Warn for degraded states, Error for failures requiring attention
Log with context — use
slog.InfoContext(ctx, ...)to correlate logs with tracesPrefer Histogram over Summary for latency metrics — Histograms support server-side aggregation and percentile queries. Every HTTP endpoint MUST have latency and error rate metrics.
Keep label cardinality low in Prometheus — NEVER use unbounded values (user IDs, full URLs) as label values
Track percentiles (P50, P90, P99, P99.9) using Histograms +
histogram_quantile()in PromQLSet up OpenTelemetry tracing on new projects — configure the TracerProvider early, then add spans everywhere
Add spans to every meaningful operation — service methods, DB queries, external API calls, message queue operations
Propagate context everywhere — context is the vehicle that carries trace_id, span_id, and deadlines across service boundaries
Enable profiling via environment variables — toggle pprof and continuous profiling on/off without redeploying
Correlate signals — inject trace_id into logs, use exemplars to link metrics to traces
A feature is not done until it is observable — declare metrics, add proper logging, create spans
awesome-prometheus-alerts provides ~500 ready-to-use alerting rules organized by technology for infrastructure and dependency monitoring
Cross-References
→ See
samber/cc-skills-golang@golang-error-handlingskill for the single handling rule.→ See
samber/cc-skills-golang@golang-troubleshootingskill for using observability signals to diagnose production issues.→ See
samber/cc-skills-golang@golang-securityskill for protecting pprof endpoints and avoiding PII in logs.→ See
samber/cc-skills-golang@golang-contextskill for propagating trace context across service boundaries.→ See
samber/cc-skills@promql-cliskill for querying and exploring PromQL expressions against Prometheus from the CLI.
Go 1.26+: slog multi-handler
For simple fan-out to multiple slog handlers, prefer stdlib slog.NewMultiHandler before adding third-party handler-composition dependencies.
logger := slog.New(slog.NewMultiHandler(
slog.NewJSONHandler(os.Stdout, nil),
auditHandler,
))Use third-party slog handler libraries only when the stdlib handler composition is insufficient.
The Five Signals
| Signal | Question it answers | Tool | When to use |
|---|---|---|---|
| Logs | What happened? | log/slog | Discrete events, errors, audit trails |
| Metrics | How much / how fast? | Prometheus client | Aggregated measurements, alerting, SLOs |
| Traces | Where did time go? | OpenTelemetry | Request flow across services, latency breakdown |
| Profiles | Why is it slow / using memory? | pprof, Pyroscope | CPU hotspots, memory leaks, lock contention |
| RUM | How do users experience it? | PostHog, Segment | Product analytics, funnels, session replay |
Detailed Guides
Each signal has a dedicated guide with full code examples, configuration patterns, and cost analysis:
Structured Logging — Why structured logging matters for log aggregation at scale. Covers
log/slogsetup, log levels (Debug/Info/Warn/Error) and when to use each, request correlation with trace IDs, context propagation withslog.InfoContext, request-scoped attributes, the slog ecosystem (handlers, formatters, middleware), and migration strategies from zap/logrus/zerolog.Metrics Collection — Prometheus client setup and the four metric types (Counter for rate-of-change, Gauge for snapshots, Histogram for latency aggregation). Deep dive: why Histograms beat Summaries (server-side aggregation, supports
histogram_quantilePromQL), naming conventions, the PromQL-as-comments convention (write queries above metric declarations for discoverability), production-grade PromQL examples, multi-window SLO burn rate alerting, and the high-cardinality label problem (why unbounded values like user IDs destroy performance).Distributed Tracing — When and how to use OpenTelemetry SDK to trace request flows across services. Covers spans (creating, attributes, status recording),
otelhttpmiddleware for HTTP instrumentation, error recording withspan.RecordError(), trace sampling (why you can't collect everything at scale), propagating trace context across service boundaries, and cost optimization.Profiling — On-demand profiling with pprof (CPU, heap, goroutine, mutex, block profiles) — how to enable it in production, secure it with auth, and toggle via environment variables without redeploying. Continuous profiling with Pyroscope for always-on performance visibility. Cost implications of each profiling type and mitigation strategies.
Real User Monitoring — Understanding how users actually experience your service. Covers product analytics (event tracking, funnels), Customer Data Platform integration, and critical compliance: GDPR/CCPA consent checks, data subject rights (user deletion endpoints), and privacy checklist for tracking. Server-side event tracking (PostHog, Segment) and identity key best practices.
Alerting — Proactive problem detection. Covers the four golden signals (latency, traffic, errors, saturation), awesome-prometheus-alerts provides ~500 ready-to-use rules by technology, Go runtime alerts (goroutine leaks, GC pressure, OOM risk), severity levels, and common mistakes that break alerting (using
irateinstead ofrate, missingfor:duration to avoid flapping).Grafana Dashboards — Prebuilt dashboards for Go runtime monitoring (heap allocation, GC pause frequency, goroutine count, CPU). Explains the standard dashboards to install, how to customize them for your service, and when each dashboard answers a different operational question.
Correlating Signals
Signals are most powerful when connected. A trace_id in your logs lets you jump from a log line to the full request trace. An exemplar on a metric links a latency spike to the exact trace that caused it.
Logs + Traces: otelslog bridge
import "go.opentelemetry.io/contrib/bridges/otelslog"
// Create a logger that automatically injects trace_id and span_id
logger := otelslog.NewHandler("my-service")
slog.SetDefault(slog.New(logger))
// Now every slog call with context includes trace correlation
slog.InfoContext(ctx, "order created", "order_id", orderID)
// Output includes: {"trace_id":"abc123", "span_id":"def456", "msg":"order created", ...}Metrics + Traces: Exemplars
// When recording a histogram observation, attach the trace_id as an exemplar
// so you can jump from a P99 spike directly to the offending trace
obs := histogram.WithLabelValues("POST", "/orders")
if eo, ok := obs.(prometheus.ExemplarObserver); ok {
eo.ObserveWithExemplar(duration, prometheus.Labels{"trace_id": traceID})
} else {
obs.Observe(duration)
}Migrating Legacy Loggers
If the project currently uses zap, logrus, or zerolog, migrate to log/slog. It is the standard library logger since Go 1.21, has a stable API, and the ecosystem has consolidated around it. Continuing with third-party loggers means maintaining an extra dependency for no benefit.
Migration strategy:
Add
slogas the new logger withslog.SetDefault()Bridge handlers during migration route slog output through the existing logger: samber/slog-zap, samber/slog-logrus, samber/slog-zerolog
Gradually replace all
zap.L().Info(...)/logrus.Info(...)/log.Info().Msg(...)calls withslog.Info(...)Once fully migrated, remove the bridge handler and the old logger dependency
Definition of Done for Observability
A feature is not production-ready until it is observable. Before marking a feature as done, verify:
[ ] Metrics declared — counters for operations/errors, histograms for latencies, gauges for saturation. Each metric var has PromQL queries and alert rules as comments above its declaration.
[ ] Logging is proper — structured key-value pairs with
slog, context variants used (slog.InfoContext), no PII in logs, errors MUST be either logged OR returned (NEVER both).[ ] Spans created — every service method, DB query, and external API call has a span with relevant attributes, errors recorded with
span.RecordError().[ ] Dashboards and alerts exist — the PromQL from your metric comments is wired into Grafana dashboards and Prometheus alerting rules. Ready-to-use alert rules for common infrastructure dependencies are available at awesome-prometheus-alerts.
[ ] RUM events tracked — key business events tracked server-side (PostHog/Segment), identity key is
user_id(not email), consent checked before tracking.
Common Mistakes
// ✗ Bad — log AND return (error gets logged multiple times up the chain)
if err != nil {
slog.Error("query failed", "error", err)
return fmt.Errorf("query: %w", err)
}
// ✓ Good — return with context, log once at the top level
if err != nil {
return fmt.Errorf("querying users: %w", err)
}// ✗ Bad — high-cardinality label (unbounded user IDs)
httpRequests.WithLabelValues(r.Method, r.URL.Path, userID).Inc()
// ✓ Good — bounded label values only
httpRequests.WithLabelValues(r.Method, routePattern).Inc()// ✗ Bad — not passing context (breaks trace propagation)
result, err := db.Query("SELECT ...")
// ✓ Good — context flows through, trace continues
result, err := db.QueryContext(ctx, "SELECT ...")// ✗ Bad — using Summary for latency (can't aggregate across instances)
prometheus.NewSummary(prometheus.SummaryOpts{
Name: "http_request_duration_seconds",
Objectives: map[float64]float64{0.99: 0.001},
})
// ✓ Good — use Histogram (aggregatable, supports histogram_quantile)
prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Buckets: prometheus.DefBuckets,
})Files
- ATTRIBUTION.mdAdded by AutoGineer917 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md13.6 KiB
- evals/evals.json43.5 KiB
- references/alerting.md7.9 KiB
- references/dashboards.md1.7 KiB
- references/logging.md8.4 KiB
- references/metrics.md23.1 KiB
- references/profiling.md3.8 KiB
- references/rum.md11.7 KiB
- references/tracing.md7.7 KiB
references/rum.md
Real User Monitoring (RUM) and Product Observability
Table of Contents
What RUM Is
RUM Capabilities
Identity Key: Use
user_id, Never EmailBackend Role in RUM
1. Server-Side Event Tracking
2. Connecting Frontend Sessions to Backend Traces
3. CDP Event Ingestion
GDPR and CCPA Compliance
Consent Management
Data Subject Rights Endpoints
Privacy Checklist
Self-Hosted vs SaaS
Cost of RUM
What RUM Is
Backend observability (logs, metrics, traces, profiles) tells you how your system behaves. RUM tells you how your users experience it. While frontend SDKs capture browser-side signals, the Go backend plays a critical role: tracking server-side business events, feeding Customer Data Platforms, and correlating user sessions with backend traces.
RUM Capabilities
| Capability | What it reveals | Example tools |
|---|---|---|
| Product Analytics | What users do — page views, clicks, feature adoption, retention | PostHog, Amplitude, Mixpanel |
| Funnel Analysis | Where users drop off in multi-step flows (signup, checkout, onboarding) | PostHog, Amplitude, Mixpanel |
| CDP | Unified user profile from all data sources — events, properties, segments | Segment, RudderStack |
Identity Key: Use user_id, Never Email
The distinct_id (identity key) used across all RUM tracking MUST be your internal, immutable user_id. NEVER use email addresses.
// ✗ Bad — email is mutable, PII, and breaks analytics when users change it
posthogClient.Enqueue(posthog.Capture{
DistinctId: user.Email, // "[email protected]" → user changes email → events split into two users
Event: "order_completed",
})
// ✓ Good — user_id is immutable, stable, and not PII
posthogClient.Enqueue(posthog.Capture{
DistinctId: user.ID, // "usr_a1b2c3" — never changes, always the same user
Event: "order_completed",
})Why email is a bad identity key:
Mutable — users change their email. Events before and after the change appear as two different users, breaking funnels, retention analysis, and cohort tracking.
PII — using email as the identity key means every event, session recording, and analytics query contains personally identifiable information. This complicates GDPR/CCPA compliance — you can't anonymize analytics without losing user identity.
Non-unique across systems — the same email might belong to different accounts in different services or environments.
Leaks into third-party systems — the distinct_id is sent to your analytics platform (PostHog, Segment, etc.). If it's an email, you've shared PII with every vendor in your analytics pipeline.
Use user_id as the identity key everywhere: PostHog DistinctId, Segment UserId, Amplitude user_id. Store email as a user property if needed for display, never as the primary key.
Backend Role in RUM
The Go backend tracks server-side events, correlates sessions with traces, and feeds data into CDPs.
1. Server-Side Event Tracking
When critical business events happen server-side (payment completed, subscription upgraded, email sent), track them from Go so they appear in the same analytics pipeline as frontend events.
import "github.com/posthog/posthog-go"
var posthogClient posthog.Client
func initPostHog() {
var err error
posthogClient, err = posthog.NewWithConfig(
os.Getenv("POSTHOG_API_KEY"),
posthog.Config{Endpoint: os.Getenv("POSTHOG_HOST")},
)
if err != nil {
slog.Error("failed to init PostHog", "error", err)
}
}
func (s *OrderService) Complete(ctx context.Context, order Order) error {
// ... business logic ...
// Track server-side event — appears alongside frontend events in PostHog
posthogClient.Enqueue(posthog.Capture{
DistinctId: order.UserID, // immutable user_id, not email
Event: "order_completed",
Properties: posthog.NewProperties().
Set("order_id", order.ID).
Set("amount", order.Total).
Set("payment_method", order.PaymentMethod).
Set("item_count", len(order.Items)),
})
return nil
}2. Connecting Frontend Sessions to Backend Traces
Pass the frontend session ID or distinct ID through HTTP headers so backend traces can be correlated with RUM sessions. When a user reports "the page was slow," you can find their session recording AND the backend trace for the same request.
func TracingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
span := trace.SpanFromContext(ctx)
// Attach RUM session ID to the backend span
if sessionID := r.Header.Get("X-Session-ID"); sessionID != "" {
span.SetAttributes(attribute.String("rum.session_id", sessionID))
}
// Attach analytics distinct ID for user correlation
if distinctID := r.Header.Get("X-Distinct-ID"); distinctID != "" {
span.SetAttributes(attribute.String("rum.distinct_id", distinctID))
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}3. CDP Event Ingestion
If you use a Customer Data Platform (Segment, RudderStack), the Go backend sends events through the CDP's server-side SDK. The CDP unifies these with frontend events into a single user profile.
import "github.com/segmentio/analytics-go/v3"
var segmentClient analytics.Client
func initSegment() {
segmentClient = analytics.New(os.Getenv("SEGMENT_WRITE_KEY"))
}
func (s *UserService) Upgrade(ctx context.Context, userID string, plan string) error {
// ... business logic ...
// Track through CDP — unified with frontend events
segmentClient.Enqueue(analytics.Track{
UserId: userID, // immutable user_id, not email
Event: "plan_upgraded",
Properties: analytics.NewProperties().
Set("plan", plan).
Set("source", "api"),
})
// Update user profile in CDP
segmentClient.Enqueue(analytics.Identify{
UserId: userID,
Traits: analytics.NewTraits().
Set("plan", plan).
Set("upgraded_at", time.Now()),
})
return nil
}GDPR and CCPA Compliance
RUM collects user behavior data — clicks, page views, session recordings. This triggers privacy regulation requirements. Compliance is not optional; violations carry heavy fines (GDPR: up to 4% of global revenue, CCPA: $7,500 per intentional violation).
Consent Management
GDPR/CCPA consent SHOULD be obtained before loading RUM SDKs or sending tracking events. This applies to both frontend scripts and server-side event tracking.
// Server-side: check consent before tracking
func (s *OrderService) Complete(ctx context.Context, order Order) error {
// ... business logic ...
// Only track if user has consented to analytics
consent := auth.ConsentFromContext(ctx)
if consent.Analytics {
posthogClient.Enqueue(posthog.Capture{
DistinctId: order.UserID,
Event: "order_completed",
Properties: posthog.NewProperties().
Set("order_id", order.ID).
Set("amount", order.Total),
})
}
return nil
}Data Subject Rights Endpoints
GDPR and CCPA require you to let users access, export, and delete their data. Implement API endpoints that propagate these requests to all systems that hold user data — your database, your analytics platform, your CDP.
// DELETE /api/users/:id/data — GDPR Article 17 "Right to Erasure"
func (h *PrivacyHandler) HandleDataDeletion(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userID := chi.URLParam(r, "id")
// 1. Delete from your database
if err := h.userRepo.DeleteAllData(ctx, userID); err != nil {
slog.ErrorContext(ctx, "failed to delete user data", "user_id", userID, "error", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// 2. Delete from analytics platform
if err := h.posthog.DeleteUser(ctx, userID); err != nil {
slog.ErrorContext(ctx, "failed to delete analytics data", "user_id", userID, "error", err)
}
// 3. Delete from CDP
if err := h.segment.DeleteUser(ctx, userID); err != nil {
slog.ErrorContext(ctx, "failed to delete CDP data", "user_id", userID, "error", err)
}
slog.InfoContext(ctx, "user data deletion completed", "user_id", userID)
w.WriteHeader(http.StatusNoContent)
}
// GET /api/users/:id/data — GDPR Article 15 "Right of Access"
func (h *PrivacyHandler) HandleDataExport(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
userID := chi.URLParam(r, "id")
export, err := h.userRepo.ExportAllData(ctx, userID)
if err != nil {
slog.ErrorContext(ctx, "failed to export user data", "user_id", userID, "error", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(export)
}Privacy Checklist
[ ] Consent before tracking — no analytics scripts load and no server-side events fire until the user consents
[ ] Consent + cookie banner — clear opt-in (not pre-checked boxes), separate consent for analytics vs marketing vs functional (frontend responsibility, but backend must respect the consent flag)
[ ] Data minimization — only collect what you need, never track PII in analytics events
[ ] Data retention policy — auto-delete old analytics data (e.g., 2 years for aggregated analytics)
[ ] Data subject rights — endpoints for data export (right of access) and deletion (right to erasure)
[ ] Data processing agreements — signed DPAs with all third-party analytics/CDP vendors
[ ] Privacy policy — lists all RUM tools, what data they collect, and how long it's retained
[ ] Identity key is not PII — use
user_id, not email, as the distinct_id across all platforms[ ] Self-hosted option — consider self-hosting (PostHog, Matomo) to keep data in your infrastructure and simplify compliance
Self-Hosted vs SaaS
| Factor | Self-hosted (PostHog, Matomo) | SaaS (Amplitude, Mixpanel) |
|---|---|---|
| Data residency | Full control — data stays in your infra | Data on vendor's servers |
| GDPR compliance | Simpler — no cross-border data transfer | Requires DPA, SCCs, or adequacy decision |
| Cost | Infrastructure cost, scales with volume | Per-event or per-seat pricing |
| Maintenance | You manage upgrades, scaling, backups | Vendor handles everything |
| Features | Catching up but improving fast | Often more polished and feature-rich |
For EU-focused products or strict data residency requirements, self-hosting PostHog is the pragmatic choice — it eliminates most GDPR concerns around cross-border data transfer.
Cost of RUM
RUM costs scale with event volume:
Event-based pricing — every page view, click, and custom event counts. A busy SaaS app can generate millions of events/month per user segment.
CDP costs — CDPs charge per tracked user and per event. Segment at scale can cost more than your entire backend infrastructure.
Mitigation:
Use server-side event filtering to drop low-value events before they reach the analytics platform
Self-host where possible to convert per-event pricing into fixed infrastructure cost
Set data retention limits on aggregated analytics
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-observability · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-observability.zip