[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6NVV4E1AQ05YMS9H48SENDD":3,"skill-same:01M6NVV4E1AQ05YMS9H48SENDD":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":14,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M6NVV4E1AQ05YMS9H48SENDD","observability",null,"Structured logging with Pino\u002FWinston, OpenTelemetry tracing, metrics collection, Grafana dashboards, and alerting rules.","rubicanjr\u002FFinCognis","rubicanjr","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F234912519?v=4","01M6NT156NND8J474G34SB3923","Rubi","01M6NT15B70RWXE1N3YV0BZY8A",0,"MIT","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fobservability\u002FSKILL.md",[],[5,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"logging","metrics","tracing","alerting","grafana","OpenTelemetry","grafana dashboards","collection","dashboards","Rules","structured","pino","structured logging","with","winston","2026-11-10 10:12:30",false,"---\nname: observability\ndescription: Structured logging with Pino\u002FWinston, OpenTelemetry tracing, metrics collection, Grafana dashboards, and alerting rules.\n---\n\n# Observability Patterns\n\nThree pillars of observability: logs, traces, and metrics. Each answers different questions.\n\n## Structured Logging with Pino (Node.js)\n\nPino is the fastest Node.js logger. Always emit JSON; never plain strings.\n\n```typescript\n\u002F\u002F logger.ts\nimport pino from 'pino'\n\nexport const logger = pino({\n  level: process.env.LOG_LEVEL ?? 'info',\n  formatters: {\n    level(label) {\n      return { level: label }        \u002F\u002F emit \"level\":\"info\" not numeric\n    }\n  },\n  base: {\n    service: process.env.SERVICE_NAME ?? 'api',\n    version: process.env.APP_VERSION ?? 'unknown',\n    env: process.env.NODE_ENV ?? 'development'\n  },\n  timestamp: pino.stdTimeFunctions.isoTime,\n  redact: {\n    paths: ['req.headers.authorization', 'body.password', '*.token'],\n    censor: '[REDACTED]'\n  }\n})\n```\n\n```typescript\n\u002F\u002F Usage examples\nimport { logger } from '.\u002Flogger'\n\n\u002F\u002F Child logger with request context\nconst reqLogger = logger.child({\n  requestId: crypto.randomUUID(),\n  userId: user.id,\n  path: req.path\n})\n\nreqLogger.info('Processing payment')\nreqLogger.warn({ amount, currency }, 'Payment above threshold')\nreqLogger.error({ err }, 'Payment failed')\n```\n\n## Structured Logging with Python (structlog)\n\n```python\n# logging_config.py\nimport structlog\nimport logging\n\nstructlog.configure(\n    processors=[\n        structlog.contextvars.merge_contextvars,\n        structlog.processors.add_log_level,\n        structlog.processors.TimeStamper(fmt=\"iso\"),\n        structlog.processors.StackInfoRenderer(),\n        structlog.processors.JSONRenderer(),\n    ],\n    wrapper_class=structlog.make_filtering_bound_logger(logging.DEBUG),\n    context_class=dict,\n    logger_factory=structlog.PrintLoggerFactory(),\n)\n\nlog = structlog.get_logger()\n```\n\n```python\n# Usage\nlog.info(\"request.received\", path=\"\u002Fapi\u002Fusers\", method=\"GET\")\nlog.warning(\"rate_limit.approaching\", user_id=user.id, count=95, limit=100)\nlog.error(\"payment.failed\", exc_info=True, order_id=order.id, amount=99.99)\n\n# Bind context for duration of request\nstructlog.contextvars.bind_contextvars(request_id=request_id, user_id=user_id)\nlog.info(\"order.created\")   # request_id and user_id included automatically\nstructlog.contextvars.clear_contextvars()\n```\n\n## Log Levels Usage Guide\n\n| Level | When to Use | Example |\n|-------|-------------|---------|\n| `trace` | Detailed execution path (dev only) | Function entry\u002Fexit, loop iterations |\n| `debug` | Diagnostic info for debugging | SQL queries, cache hit\u002Fmiss |\n| `info` | Normal operations | Request received, job started, user login |\n| `warn` | Unexpected but recoverable | Retry attempt, fallback used, slow query |\n| `error` | Errors requiring investigation | DB connection failed, 3rd party API error |\n| `fatal` | Process must exit | Config missing, port in use |\n\n```typescript\n\u002F\u002F Good log message guidelines\n\u002F\u002F ✅ Include who, what, why, and relevant IDs\nlogger.info({ userId, orderId, amount }, 'order.created')\n\n\u002F\u002F ❌ Vague message, no context\nlogger.info('Order done')\n\n\u002F\u002F ✅ Error includes the actual error object\nlogger.error({ err, orderId }, 'order.payment.failed')\n\n\u002F\u002F ❌ Error swallowed or only string\nlogger.error('Payment error: ' + err.message)\n```\n\n## Request Correlation IDs\n\nTrace a request across multiple services by propagating a unique ID.\n\n```typescript\n\u002F\u002F Express middleware: assign or forward correlation ID\nimport { randomUUID } from 'crypto'\nimport { AsyncLocalStorage } from 'async_hooks'\n\nconst requestContext = new AsyncLocalStorage\u003C{ requestId: string; userId?: string }>()\n\nexport function correlationMiddleware(req: Request, res: Response, next: NextFunction) {\n  const requestId = (req.headers['x-request-id'] as string) ?? randomUUID()\n\n  res.setHeader('x-request-id', requestId)\n\n  requestContext.run({ requestId }, () => {\n    next()\n  })\n}\n\n\u002F\u002F Get context anywhere in call stack (no prop drilling)\nexport function getRequestId(): string {\n  return requestContext.getStore()?.requestId ?? 'unknown'\n}\n\n\u002F\u002F Logger auto-includes correlation ID\nexport function getLogger() {\n  return logger.child({ requestId: getRequestId() })\n}\n```\n\n## OpenTelemetry Tracing\n\n```typescript\n\u002F\u002F tracing.ts - must be imported FIRST before other modules\nimport { NodeSDK } from '@opentelemetry\u002Fsdk-node'\nimport { OTLPTraceExporter } from '@opentelemetry\u002Fexporter-trace-otlp-http'\nimport { HttpInstrumentation } from '@opentelemetry\u002Finstrumentation-http'\nimport { ExpressInstrumentation } from '@opentelemetry\u002Finstrumentation-express'\nimport { PgInstrumentation } from '@opentelemetry\u002Finstrumentation-pg'\n\nconst sdk = new NodeSDK({\n  serviceName: process.env.SERVICE_NAME ?? 'api',\n  traceExporter: new OTLPTraceExporter({\n    url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? 'http:\u002F\u002Flocalhost:4318\u002Fv1\u002Ftraces'\n  }),\n  instrumentations: [\n    new HttpInstrumentation(),\n    new ExpressInstrumentation(),\n    new PgInstrumentation()\n  ]\n})\n\nsdk.start()\n\nprocess.on('SIGTERM', () => sdk.shutdown())\n```\n\n```typescript\n\u002F\u002F Manual spans for business logic\nimport { trace, SpanStatusCode, context } from '@opentelemetry\u002Fapi'\n\nconst tracer = trace.getTracer('payment-service')\n\nasync function processPayment(orderId: string, amount: number) {\n  return tracer.startActiveSpan('payment.process', async (span) => {\n    span.setAttributes({\n      'order.id': orderId,\n      'payment.amount': amount,\n      'payment.currency': 'USD'\n    })\n\n    try {\n      const result = await chargeCard(amount)\n      span.setStatus({ code: SpanStatusCode.OK })\n      return result\n    } catch (error) {\n      span.recordException(error as Error)\n      span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message })\n      throw error\n    } finally {\n      span.end()\n    }\n  })\n}\n```\n\n## Custom Metrics with Prometheus\n\n```typescript\n\u002F\u002F metrics.ts\nimport { Registry, Counter, Histogram, Gauge } from 'prom-client'\n\nexport const registry = new Registry()\n\n\u002F\u002F HTTP request counter\nexport const httpRequestTotal = new Counter({\n  name: 'http_requests_total',\n  help: 'Total number of HTTP requests',\n  labelNames: ['method', 'route', 'status_code'],\n  registers: [registry]\n})\n\n\u002F\u002F Request duration histogram\nexport const httpRequestDuration = new Histogram({\n  name: 'http_request_duration_seconds',\n  help: 'HTTP request duration in seconds',\n  labelNames: ['method', 'route', 'status_code'],\n  buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],\n  registers: [registry]\n})\n\n\u002F\u002F Active connections gauge\nexport const activeConnections = new Gauge({\n  name: 'active_connections',\n  help: 'Number of active WebSocket connections',\n  registers: [registry]\n})\n```\n\n```typescript\n\u002F\u002F Metrics middleware\nexport function metricsMiddleware(req: Request, res: Response, next: NextFunction) {\n  const start = Date.now()\n\n  res.on('finish', () => {\n    const duration = (Date.now() - start) \u002F 1000\n    const labels = {\n      method: req.method,\n      route: req.route?.path ?? req.path,\n      status_code: String(res.statusCode)\n    }\n    httpRequestTotal.inc(labels)\n    httpRequestDuration.observe(labels, duration)\n  })\n\n  next()\n}\n\n\u002F\u002F Metrics endpoint (scrape target for Prometheus)\napp.get('\u002Fmetrics', async (req, res) => {\n  res.set('Content-Type', registry.contentType)\n  res.send(await registry.metrics())\n})\n```\n\n## Error Tracking with Sentry\n\n```typescript\n\u002F\u002F sentry.ts\nimport * as Sentry from '@sentry\u002Fnode'\nimport { nodeProfilingIntegration } from '@sentry\u002Fprofiling-node'\n\nSentry.init({\n  dsn: process.env.SENTRY_DSN,\n  environment: process.env.NODE_ENV,\n  release: process.env.APP_VERSION,\n  integrations: [nodeProfilingIntegration()],\n  tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,\n  profilesSampleRate: 0.1,\n  beforeSend(event, hint) {\n    \u002F\u002F Strip PII from errors\n    if (event.user) {\n      delete event.user.email\n      delete event.user.ip_address\n    }\n    return event\n  }\n})\n\n\u002F\u002F Capture with context\ntry {\n  await processOrder(orderId)\n} catch (error) {\n  Sentry.withScope((scope) => {\n    scope.setTag('order.id', orderId)\n    scope.setLevel('error')\n    Sentry.captureException(error)\n  })\n  throw error\n}\n```\n\n## Grafana Dashboard Templates\n\n```json\n\u002F\u002F dashboard panel: Request Rate (PromQL)\n{\n  \"title\": \"Request Rate\",\n  \"type\": \"timeseries\",\n  \"targets\": [{\n    \"expr\": \"sum(rate(http_requests_total[5m])) by (route)\",\n    \"legendFormat\": \"{{route}}\"\n  }]\n}\n```\n\n```\n# PromQL expressions for common panels\n\n# Request rate (req\u002Fs over 5 min window)\nsum(rate(http_requests_total[5m])) by (route, method)\n\n# Error rate (%)\nsum(rate(http_requests_total{status_code=~\"5..\"}[5m]))\n  \u002F sum(rate(http_requests_total[5m])) * 100\n\n# Latency percentiles\nhistogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, route))\nhistogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, route))\nhistogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, route))\n\n# Apdex score (satisfied \u003C 0.3s, tolerated \u003C 1.2s)\n(\n  sum(rate(http_request_duration_seconds_bucket{le=\"0.3\"}[5m]))\n  + sum(rate(http_request_duration_seconds_bucket{le=\"1.2\"}[5m]))\n) \u002F 2 \u002F sum(rate(http_request_duration_seconds_count[5m]))\n```\n\n## Alert Rules (SLO-Based)\n\n```yaml\n# prometheus\u002Falerts.yml\ngroups:\n  - name: slo.alerts\n    rules:\n      # Error budget burn rate (fast burn = page immediately)\n      - alert: HighErrorRate\n        expr: |\n          (\n            sum(rate(http_requests_total{status_code=~\"5..\"}[5m]))\n            \u002F sum(rate(http_requests_total[5m]))\n          ) > 0.01\n        for: 5m\n        labels:\n          severity: critical\n        annotations:\n          summary: \"Error rate above 1% SLO\"\n          description: \"Error rate is {{ $value | humanizePercentage }}\"\n\n      # p99 latency SLO breach\n      - alert: HighLatencyP99\n        expr: |\n          histogram_quantile(0.99,\n            sum(rate(http_request_duration_seconds_bucket[5m])) by (le)\n          ) > 1.0\n        for: 10m\n        labels:\n          severity: warning\n        annotations:\n          summary: \"p99 latency above 1s SLO\"\n\n      # Service availability\n      - alert: ServiceDown\n        expr: up{job=\"api\"} == 0\n        for: 1m\n        labels:\n          severity: critical\n        annotations:\n          summary: \"API service is down\"\n```\n\n## Health Check Monitoring\n\n```typescript\n\u002F\u002F Composite health check endpoint\ninterface HealthStatus {\n  status: 'healthy' | 'degraded' | 'unhealthy'\n  checks: Record\u003Cstring, { status: string; latencyMs?: number; error?: string }>\n}\n\napp.get('\u002Fhealth\u002Fdetailed', async (req, res) => {\n  const checks: HealthStatus['checks'] = {}\n\n  \u002F\u002F Database check\n  const dbStart = Date.now()\n  try {\n    await db.execute('SELECT 1')\n    checks.database = { status: 'ok', latencyMs: Date.now() - dbStart }\n  } catch (err) {\n    checks.database = { status: 'fail', error: (err as Error).message }\n  }\n\n  \u002F\u002F Redis check\n  const redisStart = Date.now()\n  try {\n    await redis.ping()\n    checks.redis = { status: 'ok', latencyMs: Date.now() - redisStart }\n  } catch (err) {\n    checks.redis = { status: 'fail', error: (err as Error).message }\n  }\n\n  const allHealthy = Object.values(checks).every(c => c.status === 'ok')\n  const anyFailing = Object.values(checks).some(c => c.status === 'fail')\n\n  const overall: HealthStatus['status'] = allHealthy\n    ? 'healthy'\n    : anyFailing ? 'unhealthy' : 'degraded'\n\n  res.status(allHealthy ? 200 : 503).json({ status: overall, checks })\n})\n```\n\n## Dynamic Log Level in Production\n\n```typescript\n\u002F\u002F Change log level without restart\nimport { logger } from '.\u002Flogger'\n\napp.put('\u002Fadmin\u002Flog-level', requireAdminAuth, (req, res) => {\n  const { level } = req.body\n  const validLevels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']\n\n  if (!validLevels.includes(level)) {\n    return res.status(400).json({ error: 'Invalid level' })\n  }\n\n  logger.level = level\n  logger.info({ level }, 'Log level changed')\n  res.json({ level })\n})\n```\n\n## Log Rotation and Retention\n\n```bash\n# logrotate config: \u002Fetc\u002Flogrotate.d\u002Fapp\n\u002Fvar\u002Flog\u002Fapp\u002F*.log {\n  daily\n  rotate 14          # keep 14 days\n  compress\n  delaycompress\n  missingok\n  notifempty\n  postrotate\n    kill -USR1 $(cat \u002Fvar\u002Frun\u002Fapp.pid) 2>\u002Fdev\u002Fnull || true\n  endscript\n}\n```\n\n```yaml\n# Docker logging with size-based rotation\nservices:\n  api:\n    logging:\n      driver: json-file\n      options:\n        max-size: \"50m\"\n        max-file: \"5\"\n        labels: \"service,version\"\n```\n\n## APM Integration (Datadog-style without vendor lock-in)\n\n```typescript\n\u002F\u002F OpenTelemetry collector config: otel-collector.yml\n# ships to multiple backends simultaneously\nexporters:\n  otlp\u002Fdatadog:\n    endpoint: https:\u002F\u002Fapi.datadoghq.com\u002Fv1\u002Ftraces\n    headers:\n      dd-api-key: ${DD_API_KEY}\n  prometheus:\n    endpoint: 0.0.0.0:8889\n  loki:\n    endpoint: http:\u002F\u002Floki:3100\u002Floki\u002Fapi\u002Fv1\u002Fpush\n\npipelines:\n  traces:\n    receivers: [otlp]\n    processors: [batch, resourcedetection]\n    exporters: [otlp\u002Fdatadog]\n  metrics:\n    receivers: [otlp, prometheus]\n    exporters: [prometheus]\n  logs:\n    receivers: [otlp]\n    exporters: [loki]\n```\n\n**Key principle**: Correlate logs, traces, and metrics by the same `requestId`\u002F`traceId`. Emit structured JSON from day one — retrofitting is painful. Set up alerts on SLO burn rate, not absolute thresholds.\n","# Observability Patterns\n\nThree pillars of observability: logs, traces, and metrics. Each answers different questions.\n\n## Structured Logging with Pino (Node.js)\n\nPino is the fastest Node.js logger. Always emit JSON; never plain strings.\n\n```typescript\n\u002F\u002F logger.ts\nimport pino from 'pino'\n\nexport const logger = pino({\n  level: process.env.LOG_LEVEL ?? 'info',\n  formatters: {\n    level(label) {\n      return { level: label }        \u002F\u002F emit \"level\":\"info\" not numeric\n    }\n  },\n  base: {\n    service: process.env.SERVICE_NAME ?? 'api',\n    version: process.env.APP_VERSION ?? 'unknown',\n    env: process.env.NODE_ENV ?? 'development'\n  },\n  timestamp: pino.stdTimeFunctions.isoTime,\n  redact: {\n    paths: ['req.headers.authorization', 'body.password', '*.token'],\n    censor: '[REDACTED]'\n  }\n})\n```\n\n```typescript\n\u002F\u002F Usage examples\nimport { logger } from '.\u002Flogger'\n\n\u002F\u002F Child logger with request context\nconst reqLogger = logger.child({\n  requestId: crypto.randomUUID(),\n  userId: user.id,\n  path: req.path\n})\n\nreqLogger.info('Processing payment')\nreqLogger.warn({ amount, currency }, 'Payment above threshold')\nreqLogger.error({ err }, 'Payment failed')\n```\n\n## Structured Logging with Python (structlog)\n\n```python\n# logging_config.py\nimport structlog\nimport logging\n\nstructlog.configure(\n    processors=[\n        structlog.contextvars.merge_contextvars,\n        structlog.processors.add_log_level,\n        structlog.processors.TimeStamper(fmt=\"iso\"),\n        structlog.processors.StackInfoRenderer(),\n        structlog.processors.JSONRenderer(),\n    ],\n    wrapper_class=structlog.make_filtering_bound_logger(logging.DEBUG),\n    context_class=dict,\n    logger_factory=structlog.PrintLoggerFactory(),\n)\n\nlog = structlog.get_logger()\n```\n\n```python\n# Usage\nlog.info(\"request.received\", path=\"\u002Fapi\u002Fusers\", method=\"GET\")\nlog.warning(\"rate_limit.approaching\", user_id=user.id, count=95, limit=100)\nlog.error(\"payment.failed\", exc_info=True, order_id=order.id, amount=99.99)\n\n# Bind context for duration of request\nstructlog.contextvars.bind_contextvars(request_id=request_id, user_id=user_id)\nlog.info(\"order.created\")   # request_id and user_id included automatically\nstructlog.contextvars.clear_contextvars()\n```\n\n## Log Levels Usage Guide\n\n| Level | When to Use | Example |\n|-------|-------------|---------|\n| `trace` | Detailed execution path (dev only) | Function entry\u002Fexit, loop iterations |\n| `debug` | Diagnostic info for debugging | SQL queries, cache hit\u002Fmiss |\n| `info` | Normal operations | Request received, job started, user login |\n| `warn` | Unexpected but recoverable | Retry attempt, fallback used, slow query |\n| `error` | Errors requiring investigation | DB connection failed, 3rd party API error |\n| `fatal` | Process must exit | Config missing, port in use |\n\n```typescript\n\u002F\u002F Good log message guidelines\n\u002F\u002F ✅ Include who, what, why, and relevant IDs\nlogger.info({ userId, orderId, amount }, 'order.created')\n\n\u002F\u002F ❌ Vague message, no context\nlogger.info('Order done')\n\n\u002F\u002F ✅ Error includes the actual error object\nlogger.error({ err, orderId }, 'order.payment.failed')\n\n\u002F\u002F ❌ Error swallowed or only string\nlogger.error('Payment error: ' + err.message)\n```\n\n## Request Correlation IDs\n\nTrace a request across multiple services by propagating a unique ID.\n\n```typescript\n\u002F\u002F Express middleware: assign or forward correlation ID\nimport { randomUUID } from 'crypto'\nimport { AsyncLocalStorage } from 'async_hooks'\n\nconst requestContext = new AsyncLocalStorage\u003C{ requestId: string; userId?: string }>()\n\nexport function correlationMiddleware(req: Request, res: Response, next: NextFunction) {\n  const requestId = (req.headers['x-request-id'] as string) ?? randomUUID()\n\n  res.setHeader('x-request-id', requestId)\n\n  requestContext.run({ requestId }, () => {\n    next()\n  })\n}\n\n\u002F\u002F Get context anywhere in call stack (no prop drilling)\nexport function getRequestId(): string {\n  return requestContext.getStore()?.requestId ?? 'unknown'\n}\n\n\u002F\u002F Logger auto-includes correlation ID\nexport function getLogger() {\n  return logger.child({ requestId: getRequestId() })\n}\n```\n\n## OpenTelemetry Tracing\n\n```typescript\n\u002F\u002F tracing.ts - must be imported FIRST before other modules\nimport { NodeSDK } from '@opentelemetry\u002Fsdk-node'\nimport { OTLPTraceExporter } from '@opentelemetry\u002Fexporter-trace-otlp-http'\nimport { HttpInstrumentation } from '@opentelemetry\u002Finstrumentation-http'\nimport { ExpressInstrumentation } from '@opentelemetry\u002Finstrumentation-express'\nimport { PgInstrumentation } from '@opentelemetry\u002Finstrumentation-pg'\n\nconst sdk = new NodeSDK({\n  serviceName: process.env.SERVICE_NAME ?? 'api',\n  traceExporter: new OTLPTraceExporter({\n    url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? 'http:\u002F\u002Flocalhost:4318\u002Fv1\u002Ftraces'\n  }),\n  instrumentations: [\n    new HttpInstrumentation(),\n    new ExpressInstrumentation(),\n    new PgInstrumentation()\n  ]\n})\n\nsdk.start()\n\nprocess.on('SIGTERM', () => sdk.shutdown())\n```\n\n```typescript\n\u002F\u002F Manual spans for business logic\nimport { trace, SpanStatusCode, context } from '@opentelemetry\u002Fapi'\n\nconst tracer = trace.getTracer('payment-service')\n\nasync function processPayment(orderId: string, amount: number) {\n  return tracer.startActiveSpan('payment.process', async (span) => {\n    span.setAttributes({\n      'order.id': orderId,\n      'payment.amount': amount,\n      'payment.currency': 'USD'\n    })\n\n    try {\n      const result = await chargeCard(amount)\n      span.setStatus({ code: SpanStatusCode.OK })\n      return result\n    } catch (error) {\n      span.recordException(error as Error)\n      span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message })\n      throw error\n    } finally {\n      span.end()\n    }\n  })\n}\n```\n\n## Custom Metrics with Prometheus\n\n```typescript\n\u002F\u002F metrics.ts\nimport { Registry, Counter, Histogram, Gauge } from 'prom-client'\n\nexport const registry = new Registry()\n\n\u002F\u002F HTTP request counter\nexport const httpRequestTotal = new Counter({\n  name: 'http_requests_total',\n  help: 'Total number of HTTP requests',\n  labelNames: ['method', 'route', 'status_code'],\n  registers: [registry]\n})\n\n\u002F\u002F Request duration histogram\nexport const httpRequestDuration = new Histogram({\n  name: 'http_request_duration_seconds',\n  help: 'HTTP request duration in seconds',\n  labelNames: ['method', 'route', 'status_code'],\n  buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],\n  registers: [registry]\n})\n\n\u002F\u002F Active connections gauge\nexport const activeConnections = new Gauge({\n  name: 'active_connections',\n  help: 'Number of active WebSocket connections',\n  registers: [registry]\n})\n```\n\n```typescript\n\u002F\u002F Metrics middleware\nexport function metricsMiddleware(req: Request, res: Response, next: NextFunction) {\n  const start = Date.now()\n\n  res.on('finish', () => {\n    const duration = (Date.now() - start) \u002F 1000\n    const labels = {\n      method: req.method,\n      route: req.route?.path ?? req.path,\n      status_code: String(res.statusCode)\n    }\n    httpRequestTotal.inc(labels)\n    httpRequestDuration.observe(labels, duration)\n  })\n\n  next()\n}\n\n\u002F\u002F Metrics endpoint (scrape target for Prometheus)\napp.get('\u002Fmetrics', async (req, res) => {\n  res.set('Content-Type', registry.contentType)\n  res.send(await registry.metrics())\n})\n```\n\n## Error Tracking with Sentry\n\n```typescript\n\u002F\u002F sentry.ts\nimport * as Sentry from '@sentry\u002Fnode'\nimport { nodeProfilingIntegration } from '@sentry\u002Fprofiling-node'\n\nSentry.init({\n  dsn: process.env.SENTRY_DSN,\n  environment: process.env.NODE_ENV,\n  release: process.env.APP_VERSION,\n  integrations: [nodeProfilingIntegration()],\n  tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,\n  profilesSampleRate: 0.1,\n  beforeSend(event, hint) {\n    \u002F\u002F Strip PII from errors\n    if (event.user) {\n      delete event.user.email\n      delete event.user.ip_address\n    }\n    return event\n  }\n})\n\n\u002F\u002F Capture with context\ntry {\n  await processOrder(orderId)\n} catch (error) {\n  Sentry.withScope((scope) => {\n    scope.setTag('order.id', orderId)\n    scope.setLevel('error')\n    Sentry.captureException(error)\n  })\n  throw error\n}\n```\n\n## Grafana Dashboard Templates\n\n```json\n\u002F\u002F dashboard panel: Request Rate (PromQL)\n{\n  \"title\": \"Request Rate\",\n  \"type\": \"timeseries\",\n  \"targets\": [{\n    \"expr\": \"sum(rate(http_requests_total[5m])) by (route)\",\n    \"legendFormat\": \"{{route}}\"\n  }]\n}\n```\n\n```\n# PromQL expressions for common panels\n\n# Request rate (req\u002Fs over 5 min window)\nsum(rate(http_requests_total[5m])) by (route, method)\n\n# Error rate (%)\nsum(rate(http_requests_total{status_code=~\"5..\"}[5m]))\n  \u002F sum(rate(http_requests_total[5m])) * 100\n\n# Latency percentiles\nhistogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, route))\nhistogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, route))\nhistogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, route))\n\n# Apdex score (satisfied \u003C 0.3s, tolerated \u003C 1.2s)\n(\n  sum(rate(http_request_duration_seconds_bucket{le=\"0.3\"}[5m]))\n  + sum(rate(http_request_duration_seconds_bucket{le=\"1.2\"}[5m]))\n) \u002F 2 \u002F sum(rate(http_request_duration_seconds_count[5m]))\n```\n\n## Alert Rules (SLO-Based)\n\n```yaml\n# prometheus\u002Falerts.yml\ngroups:\n  - name: slo.alerts\n    rules:\n      # Error budget burn rate (fast burn = page immediately)\n      - alert: HighErrorRate\n        expr: |\n          (\n            sum(rate(http_requests_total{status_code=~\"5..\"}[5m]))\n            \u002F sum(rate(http_requests_total[5m]))\n          ) > 0.01\n        for: 5m\n        labels:\n          severity: critical\n        annotations:\n          summary: \"Error rate above 1% SLO\"\n          description: \"Error rate is {{ $value | humanizePercentage }}\"\n\n      # p99 latency SLO breach\n      - alert: HighLatencyP99\n        expr: |\n          histogram_quantile(0.99,\n            sum(rate(http_request_duration_seconds_bucket[5m])) by (le)\n          ) > 1.0\n        for: 10m\n        labels:\n          severity: warning\n        annotations:\n          summary: \"p99 latency above 1s SLO\"\n\n      # Service availability\n      - alert: ServiceDown\n        expr: up{job=\"api\"} == 0\n        for: 1m\n        labels:\n          severity: critical\n        annotations:\n          summary: \"API service is down\"\n```\n\n## Health Check Monitoring\n\n```typescript\n\u002F\u002F Composite health check endpoint\ninterface HealthStatus {\n  status: 'healthy' | 'degraded' | 'unhealthy'\n  checks: Record\u003Cstring, { status: string; latencyMs?: number; error?: string }>\n}\n\napp.get('\u002Fhealth\u002Fdetailed', async (req, res) => {\n  const checks: HealthStatus['checks'] = {}\n\n  \u002F\u002F Database check\n  const dbStart = Date.now()\n  try {\n    await db.execute('SELECT 1')\n    checks.database = { status: 'ok', latencyMs: Date.now() - dbStart }\n  } catch (err) {\n    checks.database = { status: 'fail', error: (err as Error).message }\n  }\n\n  \u002F\u002F Redis check\n  const redisStart = Date.now()\n  try {\n    await redis.ping()\n    checks.redis = { status: 'ok', latencyMs: Date.now() - redisStart }\n  } catch (err) {\n    checks.redis = { status: 'fail', error: (err as Error).message }\n  }\n\n  const allHealthy = Object.values(checks).every(c => c.status === 'ok')\n  const anyFailing = Object.values(checks).some(c => c.status === 'fail')\n\n  const overall: HealthStatus['status'] = allHealthy\n    ? 'healthy'\n    : anyFailing ? 'unhealthy' : 'degraded'\n\n  res.status(allHealthy ? 200 : 503).json({ status: overall, checks })\n})\n```\n\n## Dynamic Log Level in Production\n\n```typescript\n\u002F\u002F Change log level without restart\nimport { logger } from '.\u002Flogger'\n\napp.put('\u002Fadmin\u002Flog-level', requireAdminAuth, (req, res) => {\n  const { level } = req.body\n  const validLevels = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']\n\n  if (!validLevels.includes(level)) {\n    return res.status(400).json({ error: 'Invalid level' })\n  }\n\n  logger.level = level\n  logger.info({ level }, 'Log level changed')\n  res.json({ level })\n})\n```\n\n## Log Rotation and Retention\n\n```bash\n# logrotate config: \u002Fetc\u002Flogrotate.d\u002Fapp\n\u002Fvar\u002Flog\u002Fapp\u002F*.log {\n  daily\n  rotate 14          # keep 14 days\n  compress\n  delaycompress\n  missingok\n  notifempty\n  postrotate\n    kill -USR1 $(cat \u002Fvar\u002Frun\u002Fapp.pid) 2>\u002Fdev\u002Fnull || true\n  endscript\n}\n```\n\n```yaml\n# Docker logging with size-based rotation\nservices:\n  api:\n    logging:\n      driver: json-file\n      options:\n        max-size: \"50m\"\n        max-file: \"5\"\n        labels: \"service,version\"\n```\n\n## APM Integration (Datadog-style without vendor lock-in)\n\n```typescript\n\u002F\u002F OpenTelemetry collector config: otel-collector.yml\n# ships to multiple backends simultaneously\nexporters:\n  otlp\u002Fdatadog:\n    endpoint: https:\u002F\u002Fapi.datadoghq.com\u002Fv1\u002Ftraces\n    headers:\n      dd-api-key: ${DD_API_KEY}\n  prometheus:\n    endpoint: 0.0.0.0:8889\n  loki:\n    endpoint: http:\u002F\u002Floki:3100\u002Floki\u002Fapi\u002Fv1\u002Fpush\n\npipelines:\n  traces:\n    receivers: [otlp]\n    processors: [batch, resourcedetection]\n    exporters: [otlp\u002Fdatadog]\n  metrics:\n    receivers: [otlp, prometheus]\n    exporters: [prometheus]\n  logs:\n    receivers: [otlp]\n    exporters: [loki]\n```\n\n**Key principle**: Correlate logs, traces, and metrics by the same `requestId`\u002F`traceId`. Emit structured JSON from day one — retrofitting is painful. Set up alerts on SLO burn rate, not absolute thresholds.\n",{"name":5,"description":7},"main","70e1c350500ee750987420bbae48837afa906b7e","skills\u002Fobservability","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis","https:\u002F\u002Fgithub.com\u002Frubicanjr","linktr.ee\u002Ffinanskodu","Industrial Engineer & CIO @FinansKodu. Architecting AI-driven financial agents and autonomous workflows. 🏗️ Building systems, not just prompts.","2026-06-09 13:50:15",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add rubicanjr\u002FFinCognis --skill observability",{"tool":53,"command":54},"bunx","bunx skills add rubicanjr\u002FFinCognis --skill observability",{"tool":56,"command":57},"pnpm","pnpm dlx skills add rubicanjr\u002FFinCognis --skill observability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fobservability\u002FSKILL.md",true,[],[62,78,87,104,130,149],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":34},"01M6NWS9DAXJTADT4T5MB49X8W","workflow-router","Goal-based workflow orchestration - routes tasks to specialist agents based on user goals","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fworkflow-router\u002FSKILL.md",[],[69,70,71,72,73,74,75,76,77],"workflow router","workflow","router","orchestration","goals","goal","user","workflow orchestration","tasks",{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":34},"01M6NWS3RETSC0SHP16HP66E14","wiring","Wiring Verification","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fwiring\u002FSKILL.md",[],[80,85,86],"verification","false",{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":34},"01M6NWS0XW9CVQZBDA1EGW0TWC","websocket-patterns","Connection management, room patterns, reconnection strategies, message buffering, and binary protocol design.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fwebsocket-patterns\u002Fskill.md",[],[94,95,96,97,98,99,100,101,102,103],"websocket","patterns","websocket patterns","design","protocol","management","message","strategies","binary","connection",{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":34},"01M6NWRDQDX9ZNETAWRRMQWV52","visual-verdict","Screenshot comparison QA for frontend development. Takes a screenshot of the current implementation, scores it across multiple visual dimensions, and returns a structured PASS\u002FREVISE\u002FFAIL verdict with concrete fixes. Use when implementing UI from a design reference or verifying visual correctness.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fvisual-verdict\u002FSKILL.md",[],[111,112,113,114,115,116,117,118,119,120,121,122,123,97,124,125,126,127,128,129],"visual","verdict","visual verdict","ui","across","revise","comparison","correctness","implementing","for","fixes","dimensions","frontend","development","qa","screenshot","returns","use","frontend development",{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":34},"01M6NWR8HSNRS7MNDK2J02QYMN","verification-loop","Comprehensive verification system covering build, types, lint, tests, security, and diff review before a PR.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[137,138,85,139,140,141,142,143,144,145,146,147,148],"verification loop","loop","lint","review","security","pr","system","diff","build","tests","diff review","types",{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":153,"categories":154,"keywords":155,"publishedAt":34},"01M6NWR4HHSFR0VR5EXFRWA747","vector-db-patterns","Embedding strategies, ANN algorithms, hybrid search, RAG chunking strategies, and reranking for semantic search and retrieval.","https:\u002F\u002Fgithub.com\u002Frubicanjr\u002FFinCognis\u002Fblob\u002Fmain\u002Fskills\u002Fvector-db-patterns\u002Fskill.md",[],[156,157,158,159,95,160,161,162,163,101,164,165,166,167,168,120,169,170],"vector db patterns","vector db","db","vector","semantic search","search","embedding strategies","algorithms","chunking","semantic","retrieval","embedding","Hybrid Search","hybrid","rag"]