/diagnostics:diagnostics-basefrom diagnostics
This skill should be used whenever writing, reviewing, or refactoring error types, error messages, log statements, or any code that reports failure to a human or a machine — e.g. defining an `Error`/`Exception` class, writing `throw`, `panic!`, `raise`, or `return Err(...)`, calling `log.info/warn/error`, `console.error`, `slog`, `tracing`, `logger.*`, or composing user-facing error messages. Language-agnostic foundations; pair with a language-specific diagnostics skill for library/crate/package choices.
Ships in diagnostics. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
This skill changes how errors and logs are written. Read it fully before producing any error type, log call, or error message string. It applies regardless of language. Pair it with the appropriate language-specific diagnostics skill for concrete library choices and code patterns.
Code snippets in this skill are illustrative pseudocode. Syntax, cause-chaining API, and structured-logging field names vary by language and library — the language-specific skill is authoritative on those details.
Treat every error message and log line as a product decision, not exhaust. Before writing anything, ask: who will read this?
There are three audiences. Each needs the same triple — what happened, why it happened, what they can do — but rendered differently:
| Audience | Where they read it | What they need (what / why / what to do) |
|---|---|---|
| End user | UI dialog, CLI stderr, API response body | Plain-language summary, no jargon · just enough "why" to make the fix obvious · a concrete next step in their world ("re-enter your card", "fix the typo in email") |
| Operator / SRE | Log aggregator, error tracker, dashboards | Structured fields for filtering · severity that drives the right page · trace/request ID for correlation · fingerprint for grouping repeats · runbook-style hint when one exists |
| Developer | Debug logs, error tracker stack view, --explain docs | Full cause chain (every layer) · source location and type context · the input that triggered the failure · stable error code to pivot on |
A well-designed error object carries all three views and lets the renderer (logger, HTTP handler, CLI formatter, UI component) choose what to surface. Do not bake the rendering into the error itself — give each audience its slice from one canonical structure.
(The "anatomy of a great error" section below lists the five structural elements every error must carry. The table above shows how to render those elements per reader.)
Audience-specific reference files under references/ provide deeper
guidance for each rendering context. Load whichever matches the rendering
work in front of you:
references/end-user-errors.md — UI dialogs, CLI stderr, API response
bodies. RFC 7807/9457 Problem Details, JSON:API, Stripe and Google
AIP-193 error shapes, WCAG/ARIA form-error semantics, NN/g voice rules,
CLI source-span rendering (miette/ariadne), NO_COLOR, ICU MessageFormat
for localization.references/operator-errors.md — logs, dashboards, alerts. OpenTelemetry
attribute dictionary (exception.*, error.type, severity numbers), W3C
Trace Context propagation, fingerprinting (Sentry default + override),
sampling (head/tail, OTel samplers), Google SRE multi-burn-rate alerting,
runbook-URL embedding, log retention/cost.references/developer-errors.md — debug logs, library error types, cause
chains. Cause-chain depth in practice, stack trace handling across
V8/Rust/asyncio/Tokio, error-code naming in real systems (rustc E-codes,
Postgres SQLSTATE), Palmieri's library-vs-application framing, miette
diagnostic surface, multi-error reporting (Pydantic, GraphQL, Zod),
type-level enforcement, retriability encoded in the type.references/security-and-redaction.md — what must never appear in errors
or logs. PII, secrets, credentials, third-party leakage; classification
tags on the error type; scrubbing at the boundary; PCI/GDPR/HIPAA
touchpoints.references/inspirations.md — reference implementations worth studying
(rustc, Elm, Stripe, miette, OpenTelemetry, Postgres SQLSTATE).These references assume SKILL.md has been read — they extend it for specific rendering contexts; they do not repeat its cross-cutting rules.
The same wire-level fact carries different meaning depending on which side of the event you're on. Before reaching for a log level or designing an error type, ask: am I the producer, the receiver, or the intermediary?
| Event | If you're the producer/sender | If you're the receiver |
|---|---|---|
| 4xx HTTP response | Your bug / config / wrong assumption (WARN/ERROR) | Normal traffic (DEBUG / metrics) |
| 5xx HTTP response | Your service is broken (ERROR) | Downstream is broken (WARN until retries exhaust) |
| Parse failure on a payload | Your serializer is wrong (ERROR) | Sender sent garbage (DEBUG/WARN per taxonomy) |
| Malformed queue message | Your producer bug (ERROR) | Producer's bug; quarantine + WARN |
| RPC/DB timeout | Often you (slow/blocking call) | Often them (slow service) |
Two exceptions on the receiver side flip back toward WARN/ERROR even when you're the receiver: (a) the sender is your own code in another module — then it's still your bug, just at a different layer; (b) you have a hard contract with the sender (you own the SDK or schema) and they violated it — treat as a contract bug, log WARN/ERROR.
Audience tells how to phrase it. Role tells how seriously to take it. Answer both before writing.
Every error that crosses a meaningful boundary must have these five elements. Use this as a checklist when writing error types and messages — these are the structural fields that the audience table in Orientation #1 renders differently per reader.
A useful mnemonic before the checklist: Context → Error → Mitigation. What led to this? → What exactly failed? → What needs to happen to fix it? The five elements below are the structured form of that frame.
"failed to load config file /etc/app.toml", not "an error occurred"."field 'email' at position 3" is always better than nothing.rustc's diagnostic and a Java stack trace."while parsing startup config" → "while reading section [database]" → "value of 'port' is not a valid integer".
Each layer adds new information, never just rewording."while loading user 12345"); do
not include the word "error" or "failed" — the underlying error already
says that."operation failed" is worse than no chain. If a wrapping layer can't add
new information, propagate without wrapping.Good chain (each layer adds something):
"failed to start server"
caused by: "failed to bind to :8080"
caused by: "address already in use (os error 98)"
Bad chain (layers restate each other):
"operation failed"
caused by: "operation could not be completed"
caused by: "error in operation"
help: or hint: message dramatically increases UX quality. Include one
whenever the most common fix is known."set DATABASE_URL in your environment, e.g. postgres://localhost/myapp", not "check your configuration"."expected one of: never, always, on-failure".code field. Codes are stable across versions; message text may
change.E0308, TS2322 (rustc, tsc). Easy to
alphabetize and reference, opaque without a lookup.cfg::invalid_port, payment::card_declined.
Self-describing; groups naturally by domain.card_declined, rate_limited (Stripe). Short,
readable, easy to share verbally.references/operator-errors.md for grouping mechanics (Sentry
defaults, override patterns, code-as-fingerprint).error[CFG004]: invalid value for `snapshot_mode` in /etc/sample.properties:24
= note: expected one of: initial, never, schema_only
= help: change the value to one of the above, or remove the line to
accept the default ('initial')
= see: https://example.com/docs/snapshot-modes
Element-by-element:
invalid value for snapshot_mode (specific, lowercase, no period)/etc/sample.properties:24 (file + line)expected one of: initial, never, schema_only (states the rule)change the value... or remove the line (concrete fix)error[CFG004] (stable code) + docs URLContrast with the bad version most teams ship: "Configuration error."
Before writing an error type, place it on these four axes. The axis values drive log level, HTTP status, retry behavior, and user message.
Source of fault
user — bad input, wrong call sequence, unauthorized accessprogrammer — failed assertion, broken invariant, unreachable codesystem — disk full, OOM, network unreachable, upstream 500transient — rate limit, lock contention, temporary unavailabilityRecoverability
retriable — identical retry may succeed; advertise a backoff hintnon-retriable — retry is futile; caller must change somethingpartially-completed — side effects may have occurred; safe retry requires
an idempotency key from the client (Stripe's Idempotency-Key is the
canonical contract). Without it, "retry" cannot be made safe.Severity
fatal-process — log + exit; never panic silentlyfatal-request — operation cannot complete; propagate to boundary handlerdegraded — operation completed with caveats; log + continueVisibility
user-safe — message is safe to surface verbatim to end usersops-only — safe for internal logs, not for end-user display (may contain
internal detail, paths, IDs)partial-redact — safe for logs only after masking specific fields (e.g.,
show last 4 of card number, redact the rest)redact — contains raw PII, tokens, credentials; must be scrubbed entirely
before any loggingCarry at least source and visibility on the error type. The boundary
handler uses them to decide the log level and the user-facing message.
Encode retriability on the type as well — see
references/developer-errors.md for the field shape, Retry-After wire
contracts, and policy patterns. Redaction tags and PII handling rules live
in references/security-and-redaction.md.
Use exactly the following mapping. Deviation is a defect.
| Level | When to use |
|---|---|
| FATAL / CRITICAL | Process cannot continue. Log once, then exit (or crash). Should wake someone up. |
| ERROR | An operation failed unexpectedly and a human must investigate. Not every exception — only failures that represent a broken invariant or an unrecoverable system-level problem. A declined credit card is NOT an error. |
| WARN | Recoverable anomaly or leading indicator: retry succeeded after N attempts; deprecated config in use; resource usage crossing a threshold. Every WARN must be actionable in aggregate — if it never drives action, delete or downgrade it. |
| INFO | Notable state change in production: service started, config loaded, job completed, significant request processed. Aggregated progress in long jobs (every N records or M seconds) is fine; per-item loop output is not. |
| DEBUG | Per-request or per-item detail useful during a specific investigation, including per-record progress when genuinely needed line-by-line. Disabled in production by default; toggled via env var or feature flag. |
| TRACE | Tight loop iterations, function entry/exit, statement-level traces. Development only. Never ship enabled. |
Default production level: INFO. Libraries should default to WARN. Read
from an env var (LOG_LEVEL, RUST_LOG, etc.) so verbosity can be raised
without a redeploy.
A 4xx HTTP response is almost never an ERROR log. Default to DEBUG per-request (off in production by default; flip the level on when those need to be visible), and rely on metrics/tracing for trend visibility. Fall back to sampled INFO only when logs are the sole observability layer. Reserve ERROR for 5xx responses that indicate the service is broken, not the client.
This assumes the perspective of the server. See Orientation #2 for the inversion when the service is the client receiving 4xx/5xx from a downstream — there the default leans WARN/ERROR, not DEBUG.
The behavior-change test. A log level only earns its keep if changing it changes someone's behavior. WARN that nobody ever investigates is noise — and worse, it masks real WARNs by training people to ignore them. Audit WARN volume quarterly; downgrade or delete anything that never drives action.
Progress belongs in metrics, not logs. Logging every Nth iteration to track how far along a job is means a counter or gauge is missing — not a log line. Logs are for events; metrics are for "how far along." A per-record DEBUG line is fine during a specific investigation; a permanent Nth-record INFO line is a sign metrics infrastructure is missing.
Every log event in production must be machine-parseable. These rules are non-negotiable.
Emit JSON (or equivalent key-value) to stdout in production. Pretty-print only in development, never in production builds. Use the platform's log collection layer to route and format.
Use structured fields, not interpolated strings, for data.
log.info("user 12345 completed order 99")log.info("order completed", { user_id: "12345", order_id: "99" })The message string is a stable description of the event. The fields are the data. This lets aggregators filter and aggregate without regex.
Use OpenTelemetry semantic convention field names. Standard names mean any backend understands them without custom parsers:
service.name, trace_id, span_idexception.type, exception.message, exception.stacktraceerror.type (on spans/events)http.request.method, http.response.status_code, url.pathInclude a correlation ID on every log event at INFO and above. Request ID, trace ID, job ID — whatever is meaningful. Without it, distributed debugging is grep archaeology.
Set a log level per module / per crate / per package. Heavy dependencies (ORMs, HTTP clients) are often noisy at DEBUG — suppress them individually.
These are defects. Call them out in code review and correct them in generated output.
| Anti-pattern | Why it's wrong | Correct pattern |
|---|---|---|
"Something went wrong" | Tells the reader nothing | Name the operation and the failure |
| Stack trace as the only signal | Requires grep to understand | Add a one-line summary, an error code, a hint |
| Catching an error, logging it, then rethrowing | Duplicate entries in dashboards; hides the real origin | Log at the boundary that decides recovery; propagate everywhere else |
Swallowing errors (catch {}, _ = result) | Silent data corruption | Handle explicitly or propagate; never discard |
| Losing the cause when wrapping | Hides root cause; impossible to debug | Use the language's cause-chaining mechanism everywhere |
| Using ERROR level for normal user validation failures | Buries real problems in noise | User errors are INFO or DEBUG |
| Logging PII or credentials | Compliance and audit failure | Tag fields on the error type; scrub at the boundary (see references/security-and-redaction.md) |
| Internal module names / type names in user-facing messages | Confuses non-developers | Translate at the boundary; end-user messages use domain language |
| One enormous error enum/union for an entire application | Impossible to match exhaustively; forces consumers to handle unrelated cases | Group by domain; use opaque wrapping for cases callers won't match |
| Different field names for the same concept across services | Aggregation impossible | Adopt OTel conventions; enforce with linting |
| WARN logs that nobody ever acts on | Pure noise that masks real WARNs | Audit quarterly; downgrade or delete |
| Blaming the user ("invalid input, you fool") or sarcastic tone | Drives churn; signals carelessness; multiplies in screenshots | Focus on the problem and the recovery, not the user. Neutral, specific, non-accusatory language even when the user is wrong. |
| Parsing the message string to decide whether to retry | Brittle; breaks on message changes | Encode retriability on the type — see references/developer-errors.md |
A "boundary" is any layer where a decision is made: HTTP handler, queue
consumer, CLI main, a public module's entry point.
Inside a module: propagate typed errors. Do not log. The caller needs the information to decide what to do.
At the module's public API: ask the right question — "will the caller behave differently based on which failure mode they hit?" If yes, expose a typed enum/union; callers need to match. If no (the caller will only propagate the error or surface it to a human), convert to an opaque error type with rich context chaining. Do not expose implementation detail in public error types. (Framing borrowed from Luca Palmieri, Error Handling In Rust.)
At the application boundary: this is the only place that:
The single-log rule: an error is logged exactly once, at the boundary that decides it cannot be handled there. Any layer that propagates upward must not log. Any layer that handles (retries, substitutes a default) may log at DEBUG.
End users and operators should see a short summary by default and be able to drill in.
--verbose, "show details", error
tracker expand view).rustc --explain E0308 pattern is the gold standard: short by default,
long-form on demand.Run through this before finalizing:
code field?What SKILL.md sets; muted values are Claude Code's defaults
diagnostics@tarq is listed by tarqd/skills — review the source before installing
npx claudepluginhub tarqd/skills --plugin diagnostics4 skills in this plugin
/diagnostics-lang-skill-creatorWorkflow skill that creates a language-specific logging and diagnostics skill for a given programming language. Invoke ONLY when the user explicitly asks to create or generate a diagnostics skill, logging skill, or error handling skill for a specific language — e.g. "create a TypeScript diagnostics skill", "build me a Rust logging skill", "make a Go error handling skill for my project", "generate a Python diagnostics skill". Do NOT trigger for general questions about logging or error handling — only when the user wants to produce a new skill artifact. This skill is a multi-phase interactive workflow; do not attempt to run it silently or skip user checkpoints. Requires the diagnostics-base skill to be installed.
/diagnostics-rustLanguage-specific logging, error handling, and diagnostics patterns for Rust. Extends diagnostics-base with concrete Rust crate choices (tracing, tracing-subscriber, thiserror, anyhow, miette) and idiomatic code patterns for both libraries and applications (CLIs, HTTP services, async workers). Triggers whenever writing or reviewing error enums, `Result` returns, `?` propagation, `panic!`/`unwrap`/`expect`, or any `tracing!`/`log!` call in Rust. REQUIRES diagnostics-base to be installed — this skill does not repeat base rules, it extends them.