{"data":{"slug":"discovered-be2241850dfb41ba8070928db08e8d9979ccca337b30efcf","title":"Observability \u2014 Structured Logging, Traces, and Metrics","summary":"Implement structured logging, OpenTelemetry tracing, and PII redaction to monitor and debug production systems. Logs must include required fields such as `timestamp`, `level`, `service`, `env`, `trace_id`, and `user_id` (hashed if PII concerns exist).","url":"https:\/\/skillshunter.net\/skills\/discovered-be2241850dfb41ba8070928db08e8d9979ccca337b30efcf","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-be2241850dfb41ba8070928db08e8d9979ccca337b30efcf","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-be2241850dfb41ba8070928db08e8d9979ccca337b30efcf.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-be2241850dfb41ba8070928db08e8d9979ccca337b30efcf\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Ensure environment variables like `LOG_LEVEL` and `NODE_ENV` are set before initializing the logger. Use `OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental` to opt in to experimental attribute names. Avoid deprecated attributes like `gen_ai.prompt`.","instructions":"---\nname: observability\nversion: 2.0.0\ndescription: \"Structured logging, correlation IDs, OpenTelemetry tracing (semconv 1.41+, including GenAI conventions for Anthropic \/ OpenAI \/ AWS Bedrock \/ Azure AI \/ MCP), error tracking (Sentry), metrics, PII redaction, audit log separation. Invoke when adding logging, instrumentation, AI\/LLM observability, or debugging production issues.\"\n---\n\n# Observability \u2014 Logs, Traces, Metrics\n\n**ALWAYS invoke when adding logging, instrumentation, error tracking, or analyzing production issues.**\n\n> Three pillars: **Logs** (what happened) + **Traces** (where time was spent) + **Metrics** (how much \/ how often).\n> One signal: **correlation\/trace IDs** that thread through all three.\n\n---\n\n## 1. Structured Logging \u2014 Mandatory\n\nLogs are JSON, not text. Free-form strings can't be queried, aggregated, or alerted on.\n\n### Required fields per log line\n\n| Field | Source |\n|---|---|\n| `timestamp` | ISO-8601, UTC |\n| `level` | `trace` \/ `debug` \/ `info` \/ `warn` \/ `error` \/ `fatal` |\n| `msg` | Short human description |\n| `service` | Service name |\n| `env` | `production` \/ `staging` \/ `development` |\n| `trace_id` | OpenTelemetry trace id (W3C `traceparent`) |\n| `span_id` | Current span |\n| `request_id` | Inbound HTTP request id (mirror to `x-request-id` header) |\n| `user_id` | Authenticated user (hash if PII concerns) \u2014 **never** email\/full name |\n\n### Node.js \u2014 pino\n```ts\n\/\/ lib\/logger.ts\nimport pino from 'pino';\nimport { randomUUID } from 'crypto';\n\nexport const logger = pino({\n  level: process.env['LOG_LEVEL'] ?? 'info',\n  base: {\n    service: 'api',\n    env: process.env['NODE_ENV'],\n    pid: process.pid,\n  },\n  timestamp: pino.stdTimeFunctions.isoTime,\n  redact: {\n    paths: [\n      'req.headers.authorization',\n      'req.headers.cookie',\n      'req.body.password',\n      'req.body.token',\n      '*.password',\n      '*.creditCard',\n      '*.ssn',\n    ],\n    censor: '[REDACTED]',\n  },\n});\n\n\/\/ HTTP middleware: attach request_id + child logger to req\nexport function requestLogger(req, res, next) {\n  const requestId = req.headers['x-request-id'] ?? randomUUID();\n  res.setHeader('x-request-id', requestId);\n  req.log = logger.child({ request_id: requestId, method: req.method, path: req.path });\n  req.log.info({ event: 'request.start' });\n  res.on('finish', () => {\n    req.log.info({ event: 'request.end', status: res.statusCode, duration_ms: Date.now() - req.startTime });\n  });\n  next();\n}\n```\n\n### Python \u2014 structlog\n```python\nimport structlog, logging, sys, uuid\n\nstructlog.configure(\n    processors=[\n        structlog.contextvars.merge_contextvars,\n        structlog.processors.add_log_level,\n        structlog.processors.TimeStamper(fmt=\"iso\", utc=True),\n        structlog.processors.StackInfoRenderer(),\n        structlog.processors.format_exc_info,\n        structlog.processors.JSONRenderer(),\n    ],\n    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),\n    logger_factory=structlog.PrintLoggerFactory(file=sys.stdout),\n)\n\nlog = structlog.get_logger()\n\n# FastAPI middleware\n@app.middleware(\"http\")\nasync def request_logger(request, call_next):\n    request_id = request.headers.get(\"x-request-id\", str(uuid.uuid4()))\n    structlog.contextvars.bind_contextvars(\n        request_id=request_id, method=request.method, path=request.url.path\n    )\n    log.info(\"request.start\")\n    response = await call_next(request)\n    response.headers[\"x-request-id\"] = request_id\n    log.info(\"request.end\", status=response.status_code)\n    structlog.contextvars.clear_contextvars()\n    return response\n```\n\n### PHP \u2014 Monolog\n```php\n\/\/ config\/logging.php\n'channels' => [\n    'json' => [\n        'driver' => 'monolog',\n        'handler' => Monolog\\Handler\\StreamHandler::class,\n        'with' => ['stream' => 'php:\/\/stdout'],\n        'formatter' => Monolog\\Formatter\\JsonFormatter::class,\n        'processors' => [\n            Monolog\\Processor\\WebProcessor::class,\n            Monolog\\Processor\\UidProcessor::class,\n        ],\n    ],\n],\n```\n\n---\n\n## 2. Log Levels \u2014 Use Them Right\n\n| Level | When |\n|---|---|\n| `trace` | Verbose diagnostics, off in prod |\n| `debug` | Development helper, off in prod by default |\n| `info` | Business events: signup, payment, login, job completed |\n| `warn` | Recoverable anomaly: retry, deprecated path, fallback used |\n| `error` | Operation failed for one user\/request, system continues |\n| `fatal` | Cannot continue, process exits |\n\nDefault prod level: `info`. Errors should always page or alert. `debug` flooding logs is a cost issue.\n\n---\n\n## 3. PII Redaction \u2014 Mandatory\n\nNever log:\n- Passwords, hashes, tokens, cookies, `Authorization` headers\n- Full credit card \/ IBAN \/ SSN \/ passport\n- Plaintext email if your jurisdiction (GDPR\/LGPD) treats it as PII without legitimate basis\n- Full request body or full response body without filtering\n\nRedact at the logger level (so it can't be bypassed by a forgetful caller):\n\n```ts\n\/\/ pino redact paths (above)\n\/\/ or wrap manually:\nfunction safeBody(body: any) {\n  const out = { ...body };\n  for (const k of ['password', 'token', 'cookie', 'authorization']) {\n    if (k in out) out[k] = '[REDACTED]';\n  }\n  return out;\n}\n```\n\nFor email: log a hash of the email or the first 2 chars + domain (`jo***@example.com`). Document the policy.\n\n---\n\n## 4. Distributed Tracing \u2014 OpenTelemetry\n\nTracing answers \"where did the request spend time\" across services.\n\n### Node.js (auto-instrumentation)\n```ts\n\/\/ instrumentation.ts \u2014 load BEFORE any other import\nimport { NodeSDK } from '@opentelemetry\/sdk-node';\nimport { getNodeAutoInstrumentations } from '@opentelemetry\/auto-instrumentations-node';\nimport { OTLPTraceExporter } from '@opentelemetry\/exporter-trace-otlp-http';\nimport { Resource } from '@opentelemetry\/resources';\nimport { ATTR_SERVICE_NAME } from '@opentelemetry\/semantic-conventions';\n\nnew NodeSDK({\n  resource: new Resource({ [ATTR_SERVICE_NAME]: 'api' }),\n  traceExporter: new OTLPTraceExporter({ url: process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] }),\n  instrumentations: [getNodeAutoInstrumentations()],\n}).start();\n```\n\nRun: `node --import .\/instrumentation.js dist\/index.js`\n\n### Python (FastAPI)\n```python\nfrom opentelemetry.instrumentation.fastapi import FastAPIInstrumentor\nfrom opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor\nfrom opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor\n\nFastAPIInstrumentor.instrument_app(app)\nSQLAlchemyInstrumentor().instrument(engine=engine)\nHTTPXClientInstrumentor().instrument()\n```\n\n### Manual span \u2014 when you want to time business logic\n```ts\nimport { trace } from '@opentelemetry\/api';\nconst tracer = trace.getTracer('billing');\n\nawait tracer.startActiveSpan('charge_customer', async (span) => {\n  try {\n    span.setAttribute('customer.id', customerId);\n    const charge = await stripe.charges.create({ amount, customer: customerId });\n    span.setAttribute('charge.id', charge.id);\n    return charge;\n  } catch (err) {\n    span.recordException(err);\n    span.setStatus({ code: 2 \/* ERROR *\/ });\n    throw err;\n  } finally {\n    span.end();\n  }\n});\n```\n\n---\n\n## 5. Error Tracking \u2014 Sentry\n\nPair with structured logging. Sentry is for **alertable** errors with full stack + breadcrumbs; logs are for **everything**.\n\n### Node.js\n```ts\nimport * as Sentry from '@sentry\/node';\n\nSentry.init({\n  dsn: process.env['SENTRY_DSN'],\n  environment: process.env['NODE_ENV'],\n  tracesSampleRate: 0.1,\n  profilesSampleRate: 0.1,\n  beforeSend(event) {\n    \/\/ Defense in depth \u2014 strip if logger redaction missed it\n    if (event.request?.cookies) delete event.request.cookies;\n    if (event.request?.headers?.['authorization']) {\n      event.request.headers['authorization'] = '[REDACTED]';\n    }\n    return event;\n  },\n});\n```\n\n### Python\n```python\nimport sentry_sdk\nfrom sentry_sdk.integrations.fastapi import FastApiIntegration\nfrom sentry_sdk.scrubber import EventScrubber, DEFAULT_DENYLIST\n\nsentry_sdk.init(\n    dsn=os.environ[\"SENTRY_DSN\"],\n    environment=os.environ[\"APP_ENV\"],\n    traces_sample_rate=0.1,\n    integrations=[FastApiIntegration()],\n    event_scrubber=EventScrubber(denylist=DEFAULT_DENYLIST + [\"jwt\", \"session\"]),\n    send_default_pii=False,\n)\n```\n\n---\n\n## 6. Metrics\n\nTrack **RED** (Rate \/ Errors \/ Duration) on every endpoint and **USE** (Utilization \/ Saturation \/ Errors) on every resource.\n\nOpenTelemetry metrics + Prometheus exporter, or vendor SDK (Datadog, New Relic).\n\n```ts\nimport { metrics } from '@opentelemetry\/api';\nconst meter = metrics.getMeter('api');\n\nconst httpDuration = meter.createHistogram('http.server.duration', { unit: 'ms' });\nconst ordersCreated = meter.createCounter('orders.created');\n\nhttpDuration.record(durationMs, { method, route, status: String(statusCode) });\nordersCreated.add(1, { plan: order.plan });\n```\n\nCardinality rule: never tag with user_id, email, or unbounded values \u2014 explodes time-series storage. Use `route`, `status`, `plan`, etc.\n\n---\n\n## 6.5. AI \/ LLM Observability \u2014 OTel GenAI Semantic Conventions *(2026)*\n\nOpenTelemetry GenAI conventions (semconv \u2265 1.37, current \u2265 1.41) standardize how LLM calls are traced. They cover: **model spans**, **agent spans**, **events** (inputs\/outputs), and provider-specific conventions for **Anthropic, OpenAI, AWS Bedrock, Azure AI Inference, and MCP (Model Context Protocol)**.\n\n> Status: Development (not yet stable). Set `OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental` to opt in to current attribute names. **Do not use deprecated `gen_ai.prompt` \/ `gen_ai.completion` attributes** \u2014 they were removed in 1.28 in favor of log-based events.\n\n### Required attributes on every LLM span\n\n| Attribute | Example |\n|---|---|\n| `gen_ai.system` | `\"anthropic\"`, `\"openai\"`, `\"aws.bedrock\"`, `\"azure.ai.inference\"` |\n| `gen_ai.operation.name` | `\"chat\"`, `\"text_completion\"`, `\"embeddings\"` |\n| `gen_ai.request.model` | `\"claude-opus-4-5\"`, `\"gpt-5\"`, `\"sonnet-4-5\"` |\n| `gen_ai.response.model` | The actual model that served the request (may differ on Bedrock\/Gateway) |\n| `gen_ai.usage.input_tokens` | Numeric |\n| `gen_ai.usage.output_tokens` | Numeric |\n| `gen_ai.response.finish_reasons` | `[\"stop\"]`, `[\"length\"]`, `[\"tool_calls\"]` |\n\n### Recording inputs\/outputs as **events** (not attributes)\n\n```ts\nimport { trace, SpanKind } from '@opentelemetry\/api';\nconst tracer = trace.getTracer('llm');\n\nawait tracer.startActiveSpan('chat anthropic', { kind: SpanKind.CLIENT }, async (span) => {\n  span.setAttributes({\n    'gen_ai.system': 'anthropic',\n    'gen_ai.operation.name': 'chat',\n    'gen_ai.request.model': 'claude-opus-4-5',\n  });\n\n  \/\/ Inputs\/outputs go as EVENTS, not attributes \u2014 keeps spans cheap, allows redaction\n  span.addEvent('gen_ai.user.message', { 'gen_ai.message.content': redact(userMsg) });\n\n  const res = await anthropic.messages.create({ \/* ... *\/ });\n\n  span.setAttributes({\n    'gen_ai.response.model': res.model,\n    'gen_ai.usage.input_tokens': res.usage.input_tokens,\n    'gen_ai.usage.output_tokens': res.usage.output_tokens,\n    'gen_ai.response.finish_reasons': [res.stop_reason],\n  });\n  span.addEvent('gen_ai.assistant.message', { 'gen_ai.message.content': redact(res.content) });\n  span.end();\n  return res;\n});\n```\n\n### MCP (Model Context Protocol) spans\n\nFor agentic flows that call MCP servers:\n- `gen_ai.system`: `\"mcp\"`\n- `gen_ai.tool.name`: tool invoked\n- Span kind: `CLIENT` (your agent \u2192 MCP server)\n\n### Cost & token metrics\n\n```ts\nconst meter = metrics.getMeter('llm');\nconst tokensUsed = meter.createCounter('gen_ai.client.token.usage', { unit: '{token}' });\n\ntokensUsed.add(res.usage.input_tokens,  { 'gen_ai.system': 'anthropic', 'gen_ai.token.type': 'input',  'gen_ai.request.model': 'claude-opus-4-5' });\ntokensUsed.add(res.usage.output_tokens, { 'gen_ai.system': 'anthropic', 'gen_ai.token.type': 'output', 'gen_ai.request.model': 'claude-opus-4-5' });\n```\n\n**PII rules still apply** \u2014 redact user content in events the same way you redact request bodies in HTTP logs.\n\n---\n\n## 7. Health Checks\n\nTwo endpoints, distinct semantics:\n\n```ts\napp.get('\/healthz', (_, res) => res.json({ ok: true }));   \/\/ liveness \u2014 am I running?\n\napp.get('\/readyz', async (_, res) => {                      \/\/ readiness \u2014 can I serve?\n  const checks = await Promise.allSettled([\n    db.raw('SELECT 1'),\n    redis.ping(),\n  ]);\n  const allOk = checks.every(c => c.status === 'fulfilled');\n  res.status(allOk ? 200 : 503).json({ ok: allOk, checks });\n});\n```\n\nKubernetes uses `livenessProbe` \u2192 `\/healthz` (restart on fail) and `readinessProbe` \u2192 `\/readyz` (remove from LB on fail).\n\n---\n\n## 8. Audit Log \u2014 Separate Stream\n\nSecurity-relevant events go to a dedicated, append-only stream:\n\n- Logins (success + failure)\n- Authorization denials\n- Permission\/role changes\n- Admin actions (impersonation, data exports, deletes)\n- Payment events\n- Data access (when required by compliance: HIPAA, SOC 2)\n\nDifferent retention (often longer), different access (security team), different integrity guarantees (immutable, hash-chained).\n\n---\n\n## Pre-Commit Checklist\n\n- [ ] Logger configured with redact paths for password\/token\/cookie\/authorization\n- [ ] All endpoints emit `request.start` \/ `request.end` with `request_id`\n- [ ] Errors include stack trace and `trace_id`\n- [ ] No `console.log` \/ `print` \/ `dd()` left in code (use the logger)\n- [ ] No PII in info-level logs\n- [ ] Sentry initialized with `beforeSend` scrubber\n- [ ] Tracing initialized at process start (before app code)\n- [ ] `\/healthz` + `\/readyz` endpoints exist\n- [ ] LLM calls emit `gen_ai.*` attributes + token-usage metrics; user content redacted\n\n## FORBIDDEN\n\n| Pattern | Reason |\n|---|---|\n| `console.log(req.body)` | Leaks passwords, tokens |\n| Logger without redaction | Future caller will leak |\n| Unbounded label cardinality (user_id as metric tag) | Cost explosion |\n| Same severity for everything (all `info`) | No alerting signal |\n| Tracing in dev only | Prod is where you need it |\n| Sentry without scrubber | PII in error reports |\n| Audit log in same stream as app log | Tamper risk, retention conflict |\n\n## See Also\n\n- `secrets-management` \u2014 what NEVER to log\n- `error-handling` \u2014 Result types and error taxonomy\n- `security-baseline` \u2014 A09: Security Logging Failures\n","use_cases":["Implementing structured logging in Node.js with pino","Setting up OpenTelemetry tracing with correlation IDs","Redacting PII in logs using structlog in Python","Configuring Monolog for JSON-formatted logs in PHP"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/0x57-1\/start-vibing-stacks\/blob\/6e398b34c4dfe73ac8f809216b218856b8e02ff4\/stacks\/_shared\/skills\/observability\/SKILL.md","source_commit":"6e398b34c4dfe73ac8f809216b218856b8e02ff4","license":null,"version":null,"listing_approved_at":"2026-12-03","created_at":"2026-12-02T09:11:27.000000Z","updated_at":"2026-12-03T16:20:08.000000Z","seo_title":"Observability: Structured Logging, Tracing, and Metrics Implementation","seo_description":"Implement structured logging, OpenTelemetry tracing, and PII redaction for production systems. Ensure logs are JSON-formatted with required fields and avoid logging PII.","seo_keywords":["structured logging","observability","OpenTelemetry","tracing","PII redaction","log formatting","error tracking","metrics collection"]}}