Skip to content

EliasOulkadi/shokunin / .pack/skills/error-handler

error-handler

Verified

Design error handling, structured logging, and observability with OpenTelemetry (traces, metrics, logs), error classification, recovery patterns (retry with jitter, circuit breaker, bulkhead, timeout), error budgets/SLOs with burn rate alerts, and production incident triage. Use when user asks to implement error handling, logging, monitoring, observability, OpenTelemetry, error boundaries, circuit breakers, retry logic, or SLO tracking. Do NOT use for incident runbooks (use runbook-gen), vendor-specific APM setup (Datadog, Sentry agent config), or K8s debugging.

scripts/setup-opentelemetry.sh

View on GitHub
#!/usr/bin/env bash
set -euo pipefail

# setup-opentelemetry.sh
# Scaffolds OpenTelemetry initialization for Node.js/TypeScript projects.
# Usage: ./setup-opentelemetry.sh <service-name> [output-dir]
#   service-name  – required, e.g. "payment-api"
#   output-dir    – optional, defaults to "src/telemetry"

SERVICE_NAME="${1:?Usage: $0 <service-name> [output-dir]}"
OUT_DIR="${2:-src/telemetry}"
FILE="$OUT_DIR/instrumentation.ts"

mkdir -p "$OUT_DIR"

cat > "$FILE" << 'TYPESCRIPT'
// ─────────────────────────────────────────────────────────────
// OpenTelemetry SDK bootstrap – generated by setup-opentelemetry.sh
// Service:
TYPESCRIPT

# Append dynamic service name
echo "// Service: $SERVICE_NAME" >> "$FILE"
echo "// ─────────────────────────────────────────────────────────────" >> "$FILE"

cat >> "$FILE" << 'TYPESCRIPT'

import { NodeSDK } from '@opentelemetry/sdk-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'
import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'
import { Resource } from '@opentelemetry/resources'
import {
  SemanticResourceAttributes,
  SemanticAttributes,
} from '@opentelemetry/semantic-conventions'
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api'

// ── Debug logging (set OTEL_LOG_LEVEL=debug to enable) ──────
if (process.env.OTEL_LOG_LEVEL === 'debug') {
  diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG)
}

// ── Resource attributes ─────────────────────────────────────
const resource = new Resource({
  [SemanticResourceAttributes.SERVICE_NAME]:
    process.env.OTEL_SERVICE_NAME ||
TYPESCRIPT

echo "    '$SERVICE_NAME'," >> "$FILE"

cat >> "$FILE" << 'TYPESCRIPT'
  [SemanticResourceAttributes.SERVICE_VERSION]:
    process.env.OTEL_SERVICE_VERSION || require('../../package.json').version,
  [SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]:
    process.env.NODE_ENV || 'development',
})

// ── Exporters ────────────────────────────────────────────────
const traceExporter = new OTLPTraceExporter({
  url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/traces',
  headers: process.env.OTEL_EXPORTER_OTLP_HEADERS
    ? Object.fromEntries(
        process.env.OTEL_EXPORTER_OTLP_HEADERS.split(',').map((h) =>
          h.split('=').map((s) => s.trim())
        )
      )
    : undefined,
})

const metricExporter = new OTLPMetricExporter({
  url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/metrics',
})

const logExporter = new OTLPLogExporter({
  url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318/v1/logs',
})

// ── Metric reader ────────────────────────────────────────────
const metricReader = new PeriodicExportingMetricReader({
  exporter: metricExporter,
  exportIntervalMillis:
    parseInt(process.env.OTEL_METRIC_EXPORT_INTERVAL_MS || '') || 60_000,
})

// ── SDK instance ─────────────────────────────────────────────
const sdk = new NodeSDK({
  resource,
  traceExporter,
  logExporter,
  metricReader,
  spanProcessor: new BatchSpanProcessor(traceExporter, {
    maxExportBatchSize:
      parseInt(process.env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE || '') || 512,
    scheduledDelayMillis:
      parseInt(process.env.OTEL_BSP_SCHEDULE_DELAY || '') || 5_000,
  }),
  instrumentations: [
    getNodeAutoInstrumentations({
      '@opentelemetry/instrumentation-http': {},
      '@opentelemetry/instrumentation-express': {},
      '@opentelemetry/instrumentation-pg': {},
      '@opentelemetry/instrumentation-grpc': {},
      '@opentelemetry/instrumentation-dns': {},
    }),
  ],
})

// ── Lifecycle ────────────────────────────────────────────────
export async function startTelemetry(): Promise<void> {
  try {
    await sdk.start()
    console.log('[otel] SDK started — service:', process.env.OTEL_SERVICE_NAME || '')
  } catch (err) {
    console.error('[otel] Failed to start SDK:', err)
    process.exit(1)
  }
}

export async function shutdownTelemetry(): Promise<void> {
  try {
    await sdk.shutdown()
    console.log('[otel] SDK shut down gracefully')
  } catch (err) {
    console.error('[otel] Error during shutdown:', err)
  }
}

// Auto-start unless suppressed (e.g., in tests)
if (process.env.OTEL_SDK_DISABLED !== 'true' && process.env.NODE_ENV !== 'test') {
  startTelemetry()
}

// Graceful shutdown
process.on('SIGTERM', () => {
  shutdownTelemetry().finally(() => process.exit(0))
})
process.on('SIGINT', () => {
  shutdownTelemetry().finally(() => process.exit(0))
})
TYPESCRIPT

# ── Install instructions ─────────────────────────────────────
echo ""
echo "=== OpenTelemetry scaffold created ==="
echo "  File : $FILE"
echo ""
echo "Next steps:"
echo "  1. Install dependencies:"
echo "     npm install @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-proto"
echo "     npm install @opentelemetry/exporter-metrics-otlp-proto @opentelemetry/exporter-logs-otlp-proto"
echo "     npm install @opentelemetry/auto-instrumentations-node @opentelemetry/semantic-conventions"
echo ""
echo "  2. Add to your entrypoint (top of file, before anything else):"
echo '     import "./telemetry/instrumentation"'
echo ""
echo "  3. Set environment variables:"
echo "     OTEL_SERVICE_NAME=$SERVICE_NAME"
echo "     OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318"
echo "     OTEL_SERVICE_VERSION=1.0.0"
echo "     NODE_ENV=production"
echo ""
echo "  4. (Optional) Set sampling:"
echo "     OTEL_TRACES_SAMPLER=traceidratio"
echo "     OTEL_TRACES_SAMPLER_ARG=0.1"
echo ""
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 322kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 118kUpdated Claude CodeCodexVerifiedInstall