kid-sid/claude-spellbook/observability

Claude Code and agent skill by kid-sid/claude-spellbook

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Use when adding structured logging, instrumenting Prometheus metrics, wiring up distributed tracing with OpenTelemetry, writing alerting rules, defining SLOs and error budgets, or building a Grafana golden-signals dashboard.

Install

npx vskill@latest install kid-sid/claude-spellbook/observability

SKILL.md

The same SKILL.md was published earlier as kid-sid/claude-spellbook/observability.

Observability

Observability is the practice of instrumenting systems so you can understand their internal state from external outputs — logs, metrics, and traces.

When to Activate

  • Adding logging to a new service or endpoint
  • Setting up Prometheus metrics for a service
  • Implementing distributed tracing across services
  • Writing alerting rules or on-call runbooks
  • Defining SLOs and error budgets for a service
  • Building a Grafana dashboard for a service
  • Debugging a production issue using logs, metrics, or traces

The Three Pillars

PillarQuestion it answersBest toolWhen to reach for it
Logs"What happened?"structlog, pino, slogDebugging specific errors, audit trails
Metrics"How is the system performing?"PrometheusTrending, alerting, capacity
Traces"Why is this slow / where did it fail?"OpenTelemetryLatency debugging, distributed request flow

OpenTelemetry is the unifying standard across all three pillars: one SDK for logs, metrics, and traces, vendor-agnostic, with exporters to any backend (Grafana, Datadog, Honeycomb, Jaeger, etc.).


Structured Logging

Always emit logs as JSON. Human-readable plaintext is fine in development, but production logs must be machine-parseable. Never log sensitive data (PII, card numbers, passwords, tokens).

Mandatory Fields

Every log line must include:

FieldTypeExample
timestampISO 86012024-01-15T10:30:00.000Z
levelstringINFO
servicestringpayment-service
trace_idstringabc123...
span_idstringdef456...
request_idstringUUID per HTTP request
messagestringHuman-readable description
Log Levels
LevelWhen to useExample
DEBUGVerbose dev-only detail"Entering validatePayment()"
INFONormal operational events"Payment processed for order 123"
WARNUnexpected but recoverable"Retry attempt 2/3 for order 123"
ERRORFailure that needs attention"Payment declined: card expired"
FATAL/CRITICALService cannot continue"DB connection pool exhausted"

Rule: use INFO in production, DEBUG only in development. WARN does not page on-call. ERROR does.

Code Examples

Python with structlog:

python
import structlog
logger = structlog.get_logger()
# Configure once at startup
structlog.configure(
processors=[
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer(),
]
)
# Usage — bind context, then log
log = logger.bind(service="payment-service", request_id=request_id)
log.info("payment.processing", order_id=order_id, amount=amount)
log.error("payment.failed", order_id=order_id, error=str(e))

TypeScript with pino:

typescript
import pino from 'pino';
const logger = pino({
level: process.env.LOG_LEVEL ?? 'info',
base: { service: 'payment-service' },
});
const requestLogger = logger.child({ requestId, traceId });
requestLogger.info({ orderId, amount }, 'payment.processing');
requestLogger.error({ orderId, err }, 'payment.failed');

Go with slog (stdlib, Go 1.21+):

go
import "log/slog"
logger := slog.With(
slog.String("service", "payment-service"),
slog.String("request_id", requestID),
)
logger.Info("payment.processing",
slog.String("order_id", orderID),
slog.Float64("amount", amount),
)
logger.Error("payment.failed",
slog.String("order_id", orderID),
slog.String("error", err.Error()),
)
Correlation ID Propagation

Correlation IDs let you follow a single request across multiple services and log entries.

  • Generate request_id at the edge (API gateway or the first handler to receive the request)
  • Pass it downstream via HTTP headers: X-Request-ID or X-Correlation-ID
  • Include the ID in all log lines for the duration of that request
  • Include the ID in error responses so users can report it to support
  • In async flows (message queues, event streams): embed correlation_id in the message payload itself, not just headers

Middleware pattern (Express/Node):

typescript
import { v4 as uuidv4 } from 'uuid';
app.use((req, res, next) => {
const requestId = req.headers['x-request-id'] as string ?? uuidv4();
req.requestId = requestId;
res.setHeader('X-Request-ID', requestId);
req.log = logger.child({ requestId });
next();
});

Middleware pattern (Python/FastAPI):

python
import uuid
from starlette.middleware.base import BaseHTTPMiddleware
class CorrelationIDMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request_id = request.headers.get("x-request-id") or str(uuid.uuid4())
with structlog.contextvars.bound_contextvars(request_id=request_id):
response = await call_next(request)
response.headers["x-request-id"] = request_id
return response

Metrics with Prometheus

Prometheus is a pull-based metrics system: your service exposes a /metrics endpoint and Prometheus scrapes it on a configured interval (typically 15–30 seconds).

Metric Types
TypeUse forExample
CounterThings that only go up (requests, errors)http_requests_total
GaugeValues that go up and downactive_connections, memory_bytes
HistogramDistribution of values (latency, size)request_duration_seconds
SummaryLike histogram, but calculates quantiles client-sideAvoid — prefer Histogram

Prefer Histogram over Summary. Histograms can be aggregated across instances in PromQL; Summaries cannot.

Naming Conventions

Pattern: <namespace>_<subsystem>_<name>_<unit>

  • payment_service_http_requests_total — counter; _total suffix implies count
  • payment_service_db_query_duration_seconds — histogram; always include unit in the name
  • payment_service_cache_hit_ratio — gauge; ratio 0–1, no unit suffix needed
  • payment_service_queue_depth — gauge; current number of items in queue

Never include label values in metric names. Use labels instead:

# WRONG
http_500_errors_total
# RIGHT
http_errors_total{status="500"}
Label Cardinality Trap

Labels multiply time series. A metric with two labels each having 10 values creates 100 series. High-cardinality labels (user IDs, order IDs, full URL paths with path parameters) can create millions of series, crashing Prometheus.

python
# BAD — creates a new time series for every unique user ID
http_requests_total.labels(user_id=user.id).inc()
# GOOD — low cardinality labels only
http_requests_total.labels(method="POST", endpoint="/payments", status="200").inc()

Safe label values: HTTP method, endpoint (normalized, no IDs), status code, region, environment, service version.

RED Method (for services)

Use RED to define the minimum set of metrics for any service:

  • Rate: requests per second

``promql rate(http_requests_total[5m]) ``

  • Errors: error rate as a fraction of total traffic

``promql rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) ``

  • Duration: latency at the 95th percentile

``promql histogram_quantile(0.95, rate(request_duration_seconds_bucket[5m])) ``

USE Method (for resources)

Use USE to define metrics for infrastructure and resource-level components:

  • Utilization: percentage of time the resource is busy (e.g., CPU%, disk I/O%)
  • Saturation: work that is queued because it cannot be served immediately (e.g., run queue length)
  • Errors: error events from the resource (e.g., disk I/O errors, network drops)
Code Examples

Python with prometheus_client:

python
from prometheus_client import Counter, Histogram, start_http_server
REQUEST_COUNT = Counter(
'http_requests_total',
'Total HTTP requests',
['method', 'endpoint', 'status']
)
REQUEST_DURATION = Histogram(
'request_duration_seconds',
'HTTP request duration',
['method', 'endpoint'],
buckets=[.005, .01, .025, .05, .1, .25, .5, 1, 2.5]
)
# Usage
with REQUEST_DURATION.labels(method='POST', endpoint='/payments').time():
result = process_payment()
REQUEST_COUNT.labels(method='POST', endpoint='/payments', status='200').inc()
# Expose metrics endpoint
start_http_server(8000)

TypeScript with prom-client:

typescript
import { Counter, Histogram, collectDefaultMetrics, register } from 'prom-client';
collectDefaultMetrics({ prefix: 'payment_service_' });
const requestCount = new Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'endpoint', 'status'],
});
const requestDuration = new Histogram({
name: 'request_duration_seconds',
help: 'HTTP request duration',
labelNames: ['method', 'endpoint'],
buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5],
});
// Expose metrics endpoint
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});

Go with prometheus/client_golang:

go
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requestCount = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total HTTP requests",
}, []string{"method", "endpoint", "status"})
requestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "request_duration_seconds",
Help: "HTTP request duration",
Buckets: prometheus.DefBuckets,
}, []string{"method", "endpoint"})
)
// Expose metrics endpoint
http.Handle("/metrics", promhttp.Handler())

Distributed Tracing with OpenTelemetry

Concepts
  • Trace: the complete end-to-end journey of a single request, identified by a unique trace_id
  • Span: a single named unit of work within a trace (has a start time, end time, status, and attributes); spans form a tree
  • Context propagation: the mechanism for passing trace_id and span_id across service boundaries via HTTP headers; use the W3C traceparent header (standardized, supported everywhere)
  • Collector: a sidecar or standalone service (otel-collector) that receives span data, batches it, and forwards it to a backend (Jaeger, Tempo, etc.)
Auto-Instrumentation vs Manual Spans
  • Auto-instrumentation: instrument HTTP frameworks, DB drivers, gRPC clients automatically — get traces with zero code changes (install the SDK + one setup file)
  • Manual spans: wrap custom business logic to make it visible in traces (e.g., "processing payment", "calling fraud check API", "serializing response")

When in doubt: start with auto-instrumentation to get baseline visibility, then add manual spans where you need business context.

Setup (Python)
python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
# Bootstrap once at startup
provider = TracerProvider()
provider.add_span_processor(
BatchSpanProcessor(OTLPSpanExporter(endpoint="http://otel-collector:4317"))
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("payment-service")
# Manual span around business logic
with tracer.start_as_current_span("process_payment") as span:
span.set_attribute("order.id", order_id)
span.set_attribute("payment.amount", amount)
span.set_attribute("payment.currency", currency)
result = charge_card(card_token, amount)
span.set_attribute("payment.result", result.status)
Setup (TypeScript)

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
186
Repository forks
15
7-day trend score
26

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/kid-sid/claude-spellbook/observability/badge)](https://verified-skill.com/skills/kid-sid/claude-spellbook/observability)

Something wrong with this skill or its page? Tell us.