Skip to content
Back to skills

Go Observability Review

ASecurity

Review Go code for observability gaps: missing structured logging, broken trace context propagation, Prometheus cardinality explosions, span lifecycle errors, sensitive fields in logs, and configurations that fail silently (secrets in JSON-logged structs, unvalidated OTLP endpoints, missing global tracer provider or propagator, log rotation without retention). Dispatched by go-review-lead as a vertical reviewer. Also trigger directly when the user says "review my logging", "check my tracing",...

  • 32 stars
  • 0 votes
  • 0 copies
  • 3 views
  • Added September 19, 2026
ai-agentsgobashdockergitapisecurityperformance

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 3 files and shows the line behind each finding

Scanned December 4, 2026

npx -y skills add johnqtcg/awesome-skills --skill go-observability-review --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Go Observability Review?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Go Observability Review
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/johnqtcg-go-observability-review/badge)](https://www.skillsdirectory.com/skills/johnqtcg-go-observability-review)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: go-observability-review
description: >
  Review Go code for observability gaps: missing structured logging, broken trace
  context propagation, Prometheus cardinality explosions, span lifecycle errors,
  sensitive fields in logs, and configurations that fail silently (secrets in
  JSON-logged structs, unvalidated OTLP endpoints, missing global tracer provider
  or propagator, log rotation without retention). Dispatched by go-review-lead as
  a vertical reviewer. Also trigger directly when the user says "review my logging",
  "check my tracing", "observability review", or "are my metrics correct".
allowed-tools: Read, Grep, Glob
---

# Go Observability Review

## Purpose

Find observability defects in Go code: logging anti-patterns, trace context breaks,
metrics cardinality risks, span lifecycle errors, and telemetry configuration that
passes review and then fails without any error. This skill covers one dimension only —
do not report security, concurrency, or error-handling issues outside observability scope.

## When To Use
- Any Go change that imports `go.uber.org/zap`, `log/slog`, `go.opentelemetry.io/`, `github.com/prometheus/client_golang`, `github.com/rs/zerolog`, `gopkg.in/natefinch/lumberjack`
- Diffs adding span creation, metric registration, logging calls, exporter or logger setup
- Files under `observability/`, `telemetry/`, `instrumentation/`, `metrics/`, `tracing/`

## When NOT To Use
- Non-Go code
- Changes with no logging/tracing/metrics imports or patterns
- Security review of authentication logic → go-security-reviewer
- Deployment-side log retention (Docker log driver, kubelet, journald, Loki) and start
  scripts — not visible in Go code

## Mandatory Gates

### 1) Execution Integrity Gate
Run every grep-gated checklist item BEFORE any semantic analysis. Report the audit line:
`Grep pre-scan: X/17 items hit, Z confirmed as findings (2 semantic-only)`

### 2) Anti-Example Suppression Gate
BEFORE reporting any finding, check against the false-positive rules in
`references/go-review-anti-examples.md`. Apply all matching suppression rules.
Suppressed items must appear in the Suppressed Items section with reason.

### 3) Generated Code Exclusion Gate
Skip these files entirely — do not grep or analyze:
`*.pb.go`, `*_gen.go`, `mock_*.go`, `wire_gen.go`, `*_string.go`, any file starting with `// Code generated`

## Grep-Gated Execution Protocol

For each grep-gated item: run the grep, record HIT or MISS.
- **HIT** → proceed to semantic confirmation before reporting
- **MISS** → mark NOT FOUND, move to next item (no semantic analysis needed)

Never skip a grep step because an earlier item already found issues. Items 15 and 16
also grep the **module root** for the global setup call, because it usually lives
outside the diff (in `main` or an observability package).

```bash
# Item 1: fmt.Print* as logging (exclude test files)
grep -rn 'fmt\.Print' --include='*.go' --exclude='*_test.go' <files>

# Item 2: stdlib log (unstructured, no levels)
grep -rn 'log\.Print\|log\.Println\|log\.Printf\|log\.Fatalf\|log\.Fatalln\|log\.Fatal\b' <files>

# Item 3: logger without context propagation
grep -rn 'zap\.L()\|zap\.S()\|slog\.Info(\|slog\.Warn(\|slog\.Error(\|slog\.Debug(' <files>

# Item 4: context.Background()/TODO() in function bodies (potential chain break)
grep -rn 'context\.Background()\|context\.TODO()' <files>

# Item 5: tracer.Start without nearby defer span.End()
grep -rn '\.Start(ctx,' <files>

# Item 6: span.End() without RecordError or SetStatus
grep -rn 'span\.End()' <files>

# Item 7: Prometheus WithLabelValues (check for variable args)
grep -rn 'WithLabelValues(' <files>

# Item 8: sensitive field names in log calls
grep -rn '"password"\|"passwd"\|"token"\|"secret"\|"credential"\|"api_key"\|"apikey"' <files>

# Item 9: log.Fatal outside main package
grep -rn 'log\.Fatal\b\|log\.Fatalln\|log\.Fatalf' --include='*.go' <files>

# Item 10: HTTP handler logging without request context
grep -rn 'func.*http\.ResponseWriter.*\*http\.Request' <files>

# Item 11: zap.Error(err) as sole field (missing correlation)
grep -rn 'zap\.Error(err)' <files>

# Item 12: metric registered on the default registry
grep -rn 'prometheus\.MustRegister\|prometheus\.Register(\|promauto\.New' <files>

# Item 13: secret type redacted only through LogValue
grep -rn 'LogValue() slog\.Value' <files>

# Item 14: OTLP exporter endpoint from configuration
grep -rn 'otlp[a-z]*\.WithEndpoint' <files>

# Item 15: global tracer used — then check the module installs a global provider
grep -rn 'otel\.Tracer(' <files>
grep -rn 'otel\.SetTracerProvider(' <module root>

# Item 16: otelhttp instrumentation — then check a propagator is configured
grep -rn 'otelhttp\.NewTransport\|otelhttp\.NewHandler' <files>
grep -rn 'otel\.SetTextMapPropagator(' <module root>

# Item 17: lumberjack rotation config
grep -rn 'lumberjack\.Logger{' <files>
```

## Observability Checklist

**Items 1-17 are grep-gated. Items 18-19 are semantic-only.**

**[1] fmt.Print\* used for logging** (Medium)
Signal: `fmt.Print` in non-test Go files.
Confirm: the output is application logging (not debug output, not deliberate stdout).
Fix: replace with structured logger (`slog.InfoContext(ctx, ...)` or `logger.Info(...)`).

**[2] stdlib `log` package (no levels, no structure)** (Medium)
Signal: `log.Print*` in any file.
Confirm: not in a test helper or `main()` startup message.
Fix: replace with `slog` (Go 1.21+) or `zap`/`zerolog`.

**[3] Logger called without context — loses trace_id correlation** (High)
Signal: `zap.L()`, `zap.S()`, or `slog.Info(`/`slog.Error(`/`slog.Warn(` with no `ctx` argument.
Confirm: a request context exists in scope; this is not an init or background task.
Fix: use `logger.InfoContext(ctx, ...)` or pass ctx to `zap.L().With(zap.String("trace_id", traceID))`.

**[4] context.Background()/TODO() breaks trace propagation chain** (High)
Signal: `context.Background()` or `context.TODO()` inside a function body.
Confirm via suppression gate: NOT at service entry point (HTTP handler root, `main`, job starter).
If confirmed mid-chain: parent context is discarded; downstream spans become orphaned.
Fix: pass the incoming `ctx` parameter through; use `context.Background()` only at chain origins.

**[5] tracer.Start() without defer span.End() — span leak** (High)
Signal: `\.Start(ctx,` in a function body.
Confirm: `defer span.End()` does NOT appear in the same function scope.
Fix: add `defer span.End()` immediately after `ctx, span := tracer.Start(...)`.

**[6] Error not recorded on span — span shows no error signal** (Medium)
Signal: `span.End()` present in function.
Confirm: neither `span.RecordError(err)` nor `span.SetStatus(codes.Error, ...)` appears before the End call in an error return path.
Fix: call `span.RecordError(err); span.SetStatus(codes.Error, err.Error())` before returning the error.

**[7] Prometheus label value from variable — cardinality explosion risk** (High)
Signal: `WithLabelValues(` call.
Confirm: at least one argument is a variable (not a compile-time constant string literal).
Assess: if the variable is user-supplied (e.g., URL path, user ID, error message), it is High; if bounded enum, downgrade to Medium.
Fix: normalize dynamic values to a bounded set before using as labels; never use user input directly.

**[8] Sensitive field name in log call** (High)
Signal: `"password"`, `"token"`, `"secret"`, `"credential"`, `"api_key"` as a string literal (log field key).
Confirm: the literal is used as a key in a structured log call, not in a comment or test assertion.
Fix: redact or omit the field; log only non-sensitive identifiers (e.g., user ID, not password).
Limit: this grep sees field keys only. A secret inside a struct that is logged whole has no
such key in the call — item 13 covers that path.

**[9] log.Fatal / log.Fatalln / log.Fatalf outside main package** (Medium)
Signal: `log.Fatal` in non-main-package files.
Confirm: package declaration is NOT `package main`.
Impact: calls `os.Exit(1)` immediately, bypassing deferred cleanup, graceful shutdown hooks, and test teardown.
Fix: return an error; let the caller (ultimately main) decide on exit.

**[10] HTTP handler logging without request context** (Medium)
Signal: handler function with `http.ResponseWriter, *http.Request` signature.
Confirm: a logger call exists in the handler body but does NOT use `r.Context()` to extract the context or trace ID.
Fix: extract logger from `r.Context()` or call `logger.InfoContext(r.Context(), ...)`.

**[11] Error logged with no correlation fields** (Medium)
Signal: `zap.Error(err)` as the sole field in a zap log call.
Confirm: no other fields (request ID, trace ID, user ID) accompany the error.
Fix: add at least one correlation field: `zap.String("trace_id", span.SpanContext().TraceID().String())`.

**[12] Default-registry registration in code that runs more than once** (Medium)
Signal: `prometheus.MustRegister(...)`, `prometheus.Register(...)` or `promauto.New...` (all use the default registry).
Confirm: the registration sits in a constructor, handler, or test setup that can execute more than
once in one process (two instances of a component, one per test case, re-initialisation).
Registration in `init()` or in a package-level `var` runs once per process and is not a finding (AE-7).
Impact: the second registration of the same metric in one process panics with
`duplicate metrics collector registration attempted` (`MustRegister`, `promauto`) or returns
`AlreadyRegisteredError` (`Register`). Separate test binaries are separate processes and do not
collide. Secondary cost: default-registry metrics are shared by every test in the binary, so a
test cannot assert on its own counts.
Fix: inject a `prometheus.Registerer` through the constructor (tests pass `prometheus.NewRegistry()`),
or keep the registration at package initialisation.

**[13] Secret type redacted only through LogValue/String — leaks via JSON-logged structs** (High)
Signal: a `LogValue() slog.Value` method declaration.
Confirm all of: (a) the type has no `MarshalJSON`; (b) a struct containing a field of that type is
logged as one attribute (`slog.Info("config", "config", cfg)`, `slog.Any("cfg", cfg)`); (c) a JSON
handler is in use (`slog.NewJSONHandler`, typically production only).
Impact: slog calls `LogValue` only on a value passed directly as an attribute. A struct goes to
`encoding/json` under JSONHandler, which never calls `LogValue` or `String`, so the secret is written
in clear text; TextHandler formats with `%+v`, which calls `String()`, so development logs look
redacted. Item 8's key-name grep and key-name redaction handlers both miss it: the only key is
`config`. Measured (Go 1.26.1): JSON `"config":{"User":"u","Pass":"hunter2"}`, text `config="{User:u Pass:***}"`.
Fix: add `MarshalJSON` returning the redacted string, keeping `LogValue` and `String`; or stop
logging whole config structs.

**[14] OTLP endpoint taken from configuration without validation** (Medium)
Signal: `otlp<exporter>.WithEndpoint(` / `WithEndpointURL(`.
Confirm: the value comes from config or env and nothing before the exporter is built parses it and
requires an `http`/`https` scheme and a non-empty host; or `WithEndpoint(` (host:port only) is given a
value that carries a scheme.
Impact: on a URL parse error `WithEndpointURL` logs `otlptrace: parse endpoint url` through the otel
global logger and keeps the default endpoint (`localhost:4317` for gRPC); `New` returns no error, so
startup succeeds and spans go nowhere. A value without a scheme such as `collector:4317` parses
cleanly (scheme `collector`, empty host) and is not logged at all. Verified on otlptracegrpc v1.47.0;
check the HTTP and metric exporters' option code on your version.
Fix: parse and validate the URL yourself and fail startup (snippet in the patterns reference).

**[15] Global tracer used, but no global provider is ever installed** (High)
Signal: `otel.Tracer(` in the changed files.
Confirm: the module contains no `otel.SetTracerProvider(` — the provider is only passed explicitly
(for example to the otelhttp middleware).
Impact: `otel.Tracer(...)` then returns the no-op delegate and every `Start` yields a non-recording
span. The HTTP server span appears; the manual child spans never do, and nothing reports an error.
Measured: with the provider kept out of the global, a span recorder held the parent and the
`SpanFromContext` child, not the `otel.Tracer` child.
Not a finding when the global provider is installed at startup, even if the tracer was obtained
earlier (AE-8): the global delegate forwards once the provider is set.
Fix: call `otel.SetTracerProvider(tp)` at startup, or take the provider from the request span:
`trace.SpanFromContext(ctx).TracerProvider().Tracer(name)`.

**[16] otelhttp instrumentation without a propagator** (High)
Signal: `otelhttp.NewTransport(` or `otelhttp.NewHandler(`.
Confirm: its options contain no `otelhttp.WithPropagators(` and the module contains no
`otel.SetTextMapPropagator(`.
Impact: otelhttp's default propagator is the otel global, an empty composite until one is installed.
The outbound client span is recorded but no `traceparent` header is sent, so the trace breaks at the
service boundary. Measured (otelhttp v0.72.0): default → no `traceparent`; `WithPropagators(propagation.TraceContext{})`
→ header present. `NewHandler` uses the same default for extraction (not separately measured).
Fix: install a composite propagator globally at startup, or pass `otelhttp.WithPropagators(...)`.
The same check applies to other contrib instrumentation that accepts a `WithPropagators` option.

**[17] lumberjack rotation without retention** (Medium)
Signal: a `lumberjack.Logger{` literal.
Confirm: neither `MaxBackups` nor `MaxAge` is set (both zero).
Impact: lumberjack's documented default is to retain all old log files; `MaxSize` alone only bounds
each file, so rotated files accumulate until the disk is full.
Fix: set `MaxSize`, `MaxBackups`, `MaxAge` and `Compress` together — or log to stdout and let the
platform rotate (its retention is a deployment concern outside this review).

**[18] Critical code path lacks span coverage** *(semantic-only)* (Medium)
Assess: does the function make outbound DB calls, HTTP calls, or queue publishes without wrapping in an OTel span?
Signal of concern: function calls `db.QueryContext`, `http.Do`, or MQ publish with no `tracer.Start` in the same scope.

**[19] SLO-relevant operation lacks request metrics** *(semantic-only)* (Medium)
Assess: does the function handle a user-facing request path without incrementing a request counter and observing latency?
Signal of concern: HTTP handler or RPC handler with no `Counter.Inc()` or `Histogram.Observe()`.

## Severity Rubric

**High**: data exposure (sensitive field logged, secret leaked through a JSON-logged struct), production metric system corruption (cardinality explosion), silent trace orphaning (context break, no global provider for manual spans, no propagator at a service boundary), span leak.
**Medium**: degraded debuggability (missing correlation, stdlib log), telemetry silently exported nowhere on a bad endpoint, log disk exhaustion, duplicate default-registry registration, graceful-shutdown bypass (log.Fatal).

## Evidence Rules

- Cite the exact file path and line number.
- Quote the offending line verbatim.
- For High findings, describe the attacker/operator impact (e.g., "trace_id absent from all downstream logs for this request").
- For items 15 and 16, also state the module-root grep you ran and that it returned nothing.
- Do NOT speculate about intent. Report only what the code demonstrates.

## Output Format

```
[High|Medium] Short Title

  ID:             OBS-NNN
  Location:       path/to/file.go:line
  Impact:         production / debuggability / security impact
  Evidence:       verbatim offending line
  Recommendation: concrete fix with example
  Action:         must-fix | follow-up
```

Sections:
- **Findings** — confirmed items, sorted High → Medium
- **Suppressed Items** — items matched by anti-example gate (include matched rule + residual risk)
- **Execution Status** — the Grep pre-scan audit line from the Execution Integrity Gate + references loaded

## Load References Selectively

| File | Load when |
|------|-----------|
| `references/go-observability-patterns.md` | Writing fix recommendations; need correct slog/OTel/Prometheus/lumberjack patterns |
| `references/go-review-anti-examples.md` | Evaluating any finding for suppression; always load before reporting |

## Review Discipline

- Report observability dimension only. Do not cross into security (injection), error-handling (unwrapped errors), or performance (N+1) — those belong to their respective vertical skills.
- Execute ALL checklist items regardless of how many High findings have already been identified.
- Prefer precision over recall: a suppressed finding with documented residual risk is better than a speculative High finding.

Files in this skill

  • SKILL.md10.3 KB
  • references/go-observability-patterns.md7.2 KB
  • references/go-review-anti-examples.md4.8 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.