Generated banner for Golang Observability
Generated logo for Golang Observability

Golang Observability

Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe

  • Skill
  • Tool integration
  • Cloud and DevOps
  • MIT
  • No issues found

From the author

Golang everyday observability — the always-on signals in production. Covers structured logging with slog, Prometheus metrics, OpenTelemetry distributed tracing, continuous profiling with pprof/Pyroscope, server-side RUM event tracking, alerting, and Grafana dashboards. Apply when instrumenting Go services for production monitoring, setting up metrics or alerting, adding OpenTelemetry tracing, correlating logs with traces, migrating legacy loggers (zap/logrus/zerolog) to slog, adding observability to new features, or implementing GDPR/CCPA-compliant tracking with Customer Data Platforms (CDP). Not for temporary deep-dive performance investigation (→ See `samber/cc-skills-golang@golang-benchmark` and `samber/cc-skills-golang@golang-performance` skills).
— the description by samber

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/samber/golang-observability/download
  2. Unzip 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-observability skill 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

  1. Use structured logging with log/slog — production services MUST emit structured logs (JSON), not freeform strings

  2. Choose the right log level — Debug for development, Info for normal operations, Warn for degraded states, Error for failures requiring attention

  3. Log with context — use slog.InfoContext(ctx, ...) to correlate logs with traces

  4. Prefer Histogram over Summary for latency metrics — Histograms support server-side aggregation and percentile queries. Every HTTP endpoint MUST have latency and error rate metrics.

  5. Keep label cardinality low in Prometheus — NEVER use unbounded values (user IDs, full URLs) as label values

  6. Track percentiles (P50, P90, P99, P99.9) using Histograms + histogram_quantile() in PromQL

  7. Set up OpenTelemetry tracing on new projects — configure the TracerProvider early, then add spans everywhere

  8. Add spans to every meaningful operation — service methods, DB queries, external API calls, message queue operations

  9. Propagate context everywhere — context is the vehicle that carries trace_id, span_id, and deadlines across service boundaries

  10. Enable profiling via environment variables — toggle pprof and continuous profiling on/off without redeploying

  11. Correlate signals — inject trace_id into logs, use exemplars to link metrics to traces

  12. A feature is not done until it is observable — declare metrics, add proper logging, create spans

  13. 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-handling skill for the single handling rule.

  • → See samber/cc-skills-golang@golang-troubleshooting skill for using observability signals to diagnose production issues.

  • → See samber/cc-skills-golang@golang-security skill for protecting pprof endpoints and avoiding PII in logs.

  • → See samber/cc-skills-golang@golang-context skill for propagating trace context across service boundaries.

  • → See samber/cc-skills@promql-cli skill 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

SignalQuestion it answersToolWhen to use
LogsWhat happened?log/slogDiscrete events, errors, audit trails
MetricsHow much / how fast?Prometheus clientAggregated measurements, alerting, SLOs
TracesWhere did time go?OpenTelemetryRequest flow across services, latency breakdown
ProfilesWhy is it slow / using memory?pprof, PyroscopeCPU hotspots, memory leaks, lock contention
RUMHow do users experience it?PostHog, SegmentProduct 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/slog setup, log levels (Debug/Info/Warn/Error) and when to use each, request correlation with trace IDs, context propagation with slog.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_quantile PromQL), 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), otelhttp middleware for HTTP instrumentation, error recording with span.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 irate instead of rate, missing for: 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:

  1. Add slog as the new logger with slog.SetDefault()

  2. Bridge handlers during migration route slog output through the existing logger: samber/slog-zap, samber/slog-logrus, samber/slog-zerolog

  3. Gradually replace all zap.L().Info(...) / logrus.Info(...) / log.Info().Msg(...) calls with slog.Info(...)

  4. 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

references/tracing.md

Distributed Tracing with OpenTelemetry

→ See samber/cc-skills-golang@golang-context skill for propagating context across service boundaries. → See samber/cc-skills-golang@golang-samber-oops skill for structured errors with stack traces in spans.

When using the OpenTelemetry Go SDK, refer to the library's official documentation for up-to-date API signatures and examples.

Table of Contents

  • Why Tracing

  • OTel SDK Setup

  • Creating Spans

  • HTTP Middleware with otelhttp

  • Span Status and Recording Errors

  • Structured Errors with samber/oops

  • Trace Sampling

  • Cost of Tracing

Why Tracing

When a request crosses multiple services, logs from each service are isolated. Tracing connects them: a single trace shows the full request path with timing for every operation. This is how you answer "why was this request slow?" in a microservices architecture.

OTel SDK Setup

Set up the TracerProvider early in your application. On new projects, do this first — then add spans everywhere incrementally.

import (
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
    "go.opentelemetry.io/otel/sdk/resource"
    sdktrace "go.opentelemetry.io/otel/sdk/trace"
    semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)

func initTracer(ctx context.Context) (func(), error) {
    exporter, err := otlptracegrpc.New(ctx)
    if err != nil {
        return nil, fmt.Errorf("creating OTLP exporter: %w", err)
    }

    res, err := resource.New(ctx,
        resource.WithAttributes(
            semconv.ServiceNameKey.String("my-service"),
            semconv.ServiceVersionKey.String("1.0.0"),
        ),
    )
    if err != nil {
        return nil, fmt.Errorf("creating resource: %w", err)
    }

    tp := sdktrace.NewTracerProvider(
        sdktrace.WithBatcher(exporter),
        sdktrace.WithResource(res),
    )
    otel.SetTracerProvider(tp)

    shutdown := func() {
        _ = tp.Shutdown(context.Background())
    }
    return shutdown, nil
}

Creating Spans

Every meaningful operation should have a span. Think of spans as the building blocks of a trace — they show where time was spent.

import "go.opentelemetry.io/otel"

var tracer = otel.Tracer("myapp/order-service")

func (s *OrderService) Create(ctx context.Context, req CreateOrderRequest) (*Order, error) {
    ctx, span := tracer.Start(ctx, "OrderService.Create")
    defer span.End()

    // Add attributes that help with debugging
    span.SetAttributes(
        attribute.String("order.payment_method", req.PaymentMethod),
        attribute.Float64("order.amount", req.Amount),
    )

    order, err := s.repo.Insert(ctx, req.ToOrder())
    if err != nil {
        span.RecordError(err)
        span.SetStatus(codes.Error, err.Error())
        return nil, fmt.Errorf("inserting order: %w", err)
    }

    return order, nil
}

func (r *OrderRepo) Insert(ctx context.Context, order Order) (*Order, error) {
    ctx, span := tracer.Start(ctx, "OrderRepo.Insert")
    defer span.End()

    _, err := r.db.ExecContext(ctx, "INSERT INTO orders ...", order.ID)
    if err != nil {
        span.RecordError(err)
        span.SetStatus(codes.Error, err.Error())
        return nil, fmt.Errorf("exec insert: %w", err)
    }
    return &order, nil
}

Where to add spans — spans MUST be created for:

  • Every service method (business logic layer)

  • Every database query

  • Every external API call

  • Every message queue publish/consume

  • Any operation that takes measurable time or could fail

HTTP Middleware with otelhttp

Automatically creates spans for incoming and outgoing HTTP requests:

import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

// Incoming requests — wrap your handler
mux.Handle("/orders", otelhttp.NewHandler(orderHandler, "CreateOrder"))

// Outgoing requests — HTTP clients MUST use otelhttp for automatic span propagation
client := &http.Client{
    Transport: otelhttp.NewTransport(http.DefaultTransport),
}

Span Status and Recording Errors

import (
    "go.opentelemetry.io/otel/codes"
)

// On success — no need to set status (Unset is fine)

// On error — MUST call both RecordError() and SetStatus(Error)
if err != nil {
    span.RecordError(err)
    span.SetStatus(codes.Error, "operation failed")
    return err
}

Structured Errors with samber/oops

Standard Go errors lose critical debugging information: there's no stack trace, no structured context, and no way to attach request-scoped metadata. When an error surfaces in a trace, you see "connection refused" but not where it originated or which user/tenant was affected.

samber/oops is a drop-in error library that fills these gaps. Every oops error carries a stack trace, structured attributes, and integrates naturally with both OpenTelemetry spans and slog:

import "github.com/samber/oops"

func (s *OrderService) Create(ctx context.Context, req CreateOrderRequest) (*Order, error) {
    ctx, span := tracer.Start(ctx, "OrderService.Create")
    defer span.End()

    order, err := s.repo.Insert(ctx, req.ToOrder())
    if err != nil {
        // oops wraps the error with stack trace, structured context, and error code
        return nil, oops.
            In("order-service").
            Code("order_insert_failed").
            With("order_id", req.OrderID).
            With("user_id", req.UserID).
            Wrapf(err, "inserting order")
    }

    return order, nil
}

When this error is logged or recorded on a span, you get the full stack trace, the domain (order-service), an error code (order_insert_failed), and structured attributes (order_id, user_id) — all machine-parseable and searchable in your observability platform.

oops errors work with span.RecordError(), errors.Is/errors.As, and slog — see the samber/cc-skills-golang@golang-error-handling and samber/cc-skills-golang@golang-samber-oops skills for full usage patterns.

Trace Sampling

In high-throughput services, tracing every request is expensive. Use sampling to control the volume:

tp := sdktrace.NewTracerProvider(
    // Sample 10% of traces in production
    sdktrace.WithSampler(sdktrace.TraceIDRatioBased(0.1)),
    sdktrace.WithBatcher(exporter),
    sdktrace.WithResource(res),
)

For more nuanced control, use sdktrace.ParentBased() to respect the parent's sampling decision — this keeps traces complete across service boundaries.

Cost of Tracing

Tracing can be one of the most expensive observability signals. Every span generates data that must be serialized, transmitted, stored, and indexed. In a microservices architecture, a single user request can produce dozens or hundreds of spans across services.

Cost factors:

  • Span volume — a service handling 10k req/s with 5 spans per request generates 50k spans/s. At 100% sampling, this is enormous.

  • Span attributes — each attribute adds to the payload size. Large attributes (request/response bodies) multiply cost.

  • Storage and indexing — tracing backends (Jaeger, Tempo, Datadog) charge by volume. Unsampled traces can easily become the largest line item in your observability bill.

Mitigation:

  • Use sampling (see above) — start with 10% (TraceIDRatioBased(0.1)) and adjust based on traffic volume and budget

  • For high-throughput services, consider head-based sampling (decide at trace start) or tail-based sampling (decide after the trace completes, keeping only interesting traces like errors or slow requests)

  • Avoid attaching large payloads as span attributes — log them instead and correlate via trace_id

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