SITUATION: Monitoring & Observability Setup
Skill gerado a partir do pack templates-claude-code. Arquivo de origem: situacao/14-monitoramento-observabilidade.md. Use como baseline e adapte ao projeto antes de mudancas grandes.
Conteudo do template
CONTEXT
Use this configuration when setting up or improving observability for a live application — adding metrics, structured logging, distributed tracing, alerting, SLO definitions, or runbook creation. Observability is not an add-on — an unmonitored production service is a liability you can't reason about. This configuration ensures you can answer: "Is the service healthy right now? How do I know? What do I do when it's not?"
OBJECTIVES
- Instrument all three pillars of observability: metrics, logs, and traces
- Define SLOs/SLIs before incidents reveal you needed them
- Alert on symptoms (what users experience) not just causes (CPU usage)
- Create actionable runbooks linked from every alert
- Enable a developer to debug a production incident using only the observability stack
APPROACH RULES
Three pillars: metrics, logs, traces. Metrics tell you something is wrong. Logs tell you what happened. Traces tell you where in the system it happened. You need all three for full observability.
Alert on symptoms, not causes. "Error rate > 1%" is a symptom — users are affected. "CPU > 80%" is a cause — but doesn't necessarily mean users are impacted. Start with symptom-based alerts.
Every alert must have a runbook. If an alert fires, the on-call engineer must know what to do. An alert without a runbook is just noise that trains people to ignore alerts. Runbook link must be in the alert body.
SLO > SLA. Define Service Level Objectives (SLOs) and track your error budget. If you're burning through error budget, slow down feature development and fix reliability. If you have budget headroom, safe to move fast.
Structured logging everywhere. Never console.log("user logged in"). Always logger.info({ event: "user_login", userId: user.id, ip: req.ip }). Structured logs are queryable. Strings are not.
Correlation IDs across services. Every request gets a unique trace/correlation ID at the entry point. Every log line, every downstream call includes that ID. Without this, distributed debugging is a nightmare.
Monitor what users do, not just what systems do. Business metrics (conversion rate, checkout completions, active users) belong on the same dashboard as technical metrics. When technical metrics are fine but business metrics drop, you have a bug.
ROUTING TABLE
| If you encounter |
Then |
| No logging in the application |
Add structured logger first (pino, winston, structlog). All existing console.log → logger.info/error. |
| console.log in production code |
Replace with structured logger. console.log is not queryable, not leveled, not structured. |
| Alert without runbook |
Write the runbook before the alert goes live. Template: What is this alert? What is the impact? What are the steps? |
| P99 latency not tracked |
Add P95 and P99 latency histograms. Averages hide worst-case user experience. |
| Errors logged without stack trace |
Fix immediately. Logs without stack traces are unusable for debugging. |
| Alert firing with no action taken |
Either fix the condition or remove the alert. Alert fatigue kills incident response. |
| No distributed tracing |
Add OpenTelemetry SDK. Instrument HTTP calls, DB queries, queue operations. |
| SLO not defined |
Define Error Rate SLO (e.g., 99.9% of requests succeed) and Latency SLO (P95 < 500ms). |
| Logs growing without limit |
Add log rotation. Set retention policies. Production logs: 30 days hot, 90 days cold. |
| Multiple services with no centralized logging |
Implement log aggregation: ELK stack, Loki + Grafana, or Datadog/New Relic. |
Three Pillars Implementation Guide
Metrics (What is happening)
// Using prom-client (Node.js)
import { Counter, Histogram, register } from 'prom-client'
const httpRequestDuration = new Histogram({
name: 'http_request_duration_seconds',
help: 'HTTP request duration in seconds',
labelNames: ['method', 'route', 'status_code'],
buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5]
})
const httpRequestTotal = new Counter({
name: 'http_requests_total',
help: 'Total HTTP requests',
labelNames: ['method', 'route', 'status_code']
})
// Expose at /metrics endpoint
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType)
res.send(await register.metrics())
})
Logs (What happened)
// Using pino (Node.js)
import pino from 'pino'
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
base: { service: 'api', version: process.env.APP_VERSION },
timestamp: pino.stdTimeFunctions.isoTime
})
// ✅ Good: structured, queryable
logger.info({ event: 'payment_processed', userId, amount, currency }, 'Payment processed')
logger.error({ err: error, userId, requestId }, 'Payment failed')
// ❌ Bad: string only, not queryable
console.log(`Payment failed for user ${userId}: ${error.message}`)
Traces (Where it happened)
// Using OpenTelemetry
import { trace, context, propagation } from '@opentelemetry/api'
const tracer = trace.getTracer('my-service')
async function processOrder(orderId: string) {
const span = tracer.startSpan('processOrder', {
attributes: { 'order.id': orderId }
})
try {
await span.setAttribute('order.status', 'processing')
const result = await doWork(orderId)
span.setStatus({ code: SpanStatusCode.OK })
return result
} catch (err) {
span.recordException(err)
span.setStatus({ code: SpanStatusCode.ERROR })
throw err
} finally {
span.end()
}
}
SLO Definition Template
service: checkout-api
slos:
- name: Checkout Success Rate
description: Percentage of checkout requests that succeed
sli: (sum of successful checkout requests) / (sum of all checkout requests)
target: 99.5%
measurement_window: 30 days
error_budget: 0.5% → 216 minutes/month allowable downtime
- name: Checkout Latency
description: P95 latency for checkout endpoint
sli: 95th percentile response time
target: < 1000ms
measurement_window: 30 days
alerts:
- name: Checkout Error Rate Burn
condition: Error budget burn rate > 5× for 1 hour
severity: page (wake someone up)
runbook: docs/runbooks/checkout-errors.md
DO NOT
- DO NOT set up monitoring after the first incident — it's too late then
- DO NOT log PII (email, name, phone, card numbers) — mask or hash before logging
- DO NOT create alerts that can't be acted on — each alert needs a clear response procedure
- DO NOT use average latency as your primary metric — use P95 and P99
- DO NOT monitor only infrastructure (CPU, memory) and ignore application-level health
- DO NOT alert with CRITICAL severity on things that are informational
- DO NOT delete old logs without understanding retention requirements (GDPR, compliance)
OUTPUT FORMAT
For each monitoring setup, deliver:
Observability Coverage Matrix:
| Signal | Tool | Coverage | Retention | Alert? |
|--------|------|----------|-----------|--------|
| App logs | Loki | INFO+ in prod. DEBUG in staging | 30 days | On ERROR+ |
| Infrastructure metrics | Prometheus | CPU, memory, disk, network | 90 days | On threshold |
| App metrics | Prometheus | Request rate, error rate, latency histograms | 90 days | On SLO burn |
| Traces | Jaeger/Tempo | Sample rate: 10% prod, 100% staging | 7 days | On trace error |
| Uptime | Healthchecks.io | External probe every 60s | 365 days | On unavailable |
**Runbook Inventory:**
| Alert | Runbook | Owner | Last Verified |
|-------|---------|-------|---------------|
| High error rate | docs/runbooks/high-error-rate.md | Platform | 2024-01-01 |
QUALITY GATES
1---2name: tpl-situacao-monitoramento-observabilidade3description: Template do pack (situacao/14-monitoramento-observabilidade.md). Orienta o agente em tarefas situacionais como debug, seguranca e refactor alinhado a esse contexto.4metadata:5 source: https://skillmd.com/skills/artubss/tpl-situacao-monitoramento-observabilidade6 version: 1.0.07 source_template: situacao/14-monitoramento-observabilidade.md8 generated_by: install_pack_templates_as_claude_skills9---1011# SITUATION: Monitoring & Observability Setup1213Skill gerado a partir do pack `templates-claude-code`. Arquivo de origem: `situacao/14-monitoramento-observabilidade.md`. Use como baseline e adapte ao projeto antes de mudancas grandes.1415## Conteudo do template1617## CONTEXT18Use this configuration when setting up or improving observability for a live application — adding metrics, structured logging, distributed tracing, alerting, SLO definitions, or runbook creation. Observability is not an add-on — an unmonitored production service is a liability you can't reason about. This configuration ensures you can answer: "Is the service healthy right now? How do I know? What do I do when it's not?"1920## OBJECTIVES21- Instrument all three pillars of observability: metrics, logs, and traces22- Define SLOs/SLIs before incidents reveal you needed them23- Alert on symptoms (what users experience) not just causes (CPU usage)24- Create actionable runbooks linked from every alert25- Enable a developer to debug a production incident using only the observability stack2627## APPROACH RULES28291. **Three pillars: metrics, logs, traces.** Metrics tell you something is wrong. Logs tell you what happened. Traces tell you where in the system it happened. You need all three for full observability.30312. **Alert on symptoms, not causes.** "Error rate > 1%" is a symptom — users are affected. "CPU > 80%" is a cause — but doesn't necessarily mean users are impacted. Start with symptom-based alerts.32333. **Every alert must have a runbook.** If an alert fires, the on-call engineer must know what to do. An alert without a runbook is just noise that trains people to ignore alerts. Runbook link must be in the alert body.34354. **SLO > SLA.** Define Service Level Objectives (SLOs) and track your error budget. If you're burning through error budget, slow down feature development and fix reliability. If you have budget headroom, safe to move fast.36375. **Structured logging everywhere.** Never `console.log("user logged in")`. Always `logger.info({ event: "user_login", userId: user.id, ip: req.ip })`. Structured logs are queryable. Strings are not.38396. **Correlation IDs across services.** Every request gets a unique trace/correlation ID at the entry point. Every log line, every downstream call includes that ID. Without this, distributed debugging is a nightmare.40417. **Monitor what users do, not just what systems do.** Business metrics (conversion rate, checkout completions, active users) belong on the same dashboard as technical metrics. When technical metrics are fine but business metrics drop, you have a bug.4243## ROUTING TABLE4445| If you encounter | Then |46|-----------------|------|47| No logging in the application | Add structured logger first (pino, winston, structlog). All existing console.log → logger.info/error. |48| console.log in production code | Replace with structured logger. console.log is not queryable, not leveled, not structured. |49| Alert without runbook | Write the runbook before the alert goes live. Template: What is this alert? What is the impact? What are the steps? |50| P99 latency not tracked | Add P95 and P99 latency histograms. Averages hide worst-case user experience. |51| Errors logged without stack trace | Fix immediately. Logs without stack traces are unusable for debugging. |52| Alert firing with no action taken | Either fix the condition or remove the alert. Alert fatigue kills incident response. |53| No distributed tracing | Add OpenTelemetry SDK. Instrument HTTP calls, DB queries, queue operations. |54| SLO not defined | Define Error Rate SLO (e.g., 99.9% of requests succeed) and Latency SLO (P95 < 500ms). |55| Logs growing without limit | Add log rotation. Set retention policies. Production logs: 30 days hot, 90 days cold. |56| Multiple services with no centralized logging | Implement log aggregation: ELK stack, Loki + Grafana, or Datadog/New Relic. |5758## Three Pillars Implementation Guide5960### Metrics (What is happening)61```typescript62// Using prom-client (Node.js)63import { Counter, Histogram, register } from 'prom-client'6465const httpRequestDuration = new Histogram({66 name: 'http_request_duration_seconds',67 help: 'HTTP request duration in seconds',68 labelNames: ['method', 'route', 'status_code'],69 buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5]70})7172const httpRequestTotal = new Counter({73 name: 'http_requests_total',74 help: 'Total HTTP requests',75 labelNames: ['method', 'route', 'status_code']76})7778// Expose at /metrics endpoint79app.get('/metrics', async (req, res) => {80 res.set('Content-Type', register.contentType)81 res.send(await register.metrics())82})83```8485### Logs (What happened)86```typescript87// Using pino (Node.js)88import pino from 'pino'8990const logger = pino({91 level: process.env.LOG_LEVEL || 'info',92 base: { service: 'api', version: process.env.APP_VERSION },93 timestamp: pino.stdTimeFunctions.isoTime94})9596// ✅ Good: structured, queryable97logger.info({ event: 'payment_processed', userId, amount, currency }, 'Payment processed')98logger.error({ err: error, userId, requestId }, 'Payment failed')99100// ❌ Bad: string only, not queryable101console.log(`Payment failed for user ${userId}: ${error.message}`)102```103104### Traces (Where it happened)105```typescript106// Using OpenTelemetry107import { trace, context, propagation } from '@opentelemetry/api'108109const tracer = trace.getTracer('my-service')110111async function processOrder(orderId: string) {112 const span = tracer.startSpan('processOrder', {113 attributes: { 'order.id': orderId }114 })115 116 try {117 await span.setAttribute('order.status', 'processing')118 const result = await doWork(orderId)119 span.setStatus({ code: SpanStatusCode.OK })120 return result121 } catch (err) {122 span.recordException(err)123 span.setStatus({ code: SpanStatusCode.ERROR })124 throw err125 } finally {126 span.end()127 }128}129```130131## SLO Definition Template132133```yaml134service: checkout-api135slos:136 - name: Checkout Success Rate137 description: Percentage of checkout requests that succeed138 sli: (sum of successful checkout requests) / (sum of all checkout requests)139 target: 99.5%140 measurement_window: 30 days141 error_budget: 0.5% → 216 minutes/month allowable downtime142143 - name: Checkout Latency144 description: P95 latency for checkout endpoint145 sli: 95th percentile response time146 target: < 1000ms147 measurement_window: 30 days148149alerts:150 - name: Checkout Error Rate Burn151 condition: Error budget burn rate > 5× for 1 hour152 severity: page (wake someone up)153 runbook: docs/runbooks/checkout-errors.md154```155156## DO NOT157158- **DO NOT** set up monitoring after the first incident — it's too late then159- **DO NOT** log PII (email, name, phone, card numbers) — mask or hash before logging160- **DO NOT** create alerts that can't be acted on — each alert needs a clear response procedure161- **DO NOT** use average latency as your primary metric — use P95 and P99162- **DO NOT** monitor only infrastructure (CPU, memory) and ignore application-level health163- **DO NOT** alert with CRITICAL severity on things that are informational164- **DO NOT** delete old logs without understanding retention requirements (GDPR, compliance)165166## OUTPUT FORMAT167168For each monitoring setup, deliver:169170**Observability Coverage Matrix:**171```markdown172| Signal | Tool | Coverage | Retention | Alert? |173|--------|------|----------|-----------|--------|174| App logs | Loki | INFO+ in prod. DEBUG in staging | 30 days | On ERROR+ |175| Infrastructure metrics | Prometheus | CPU, memory, disk, network | 90 days | On threshold |176| App metrics | Prometheus | Request rate, error rate, latency histograms | 90 days | On SLO burn |177| Traces | Jaeger/Tempo | Sample rate: 10% prod, 100% staging | 7 days | On trace error |178| Uptime | Healthchecks.io | External probe every 60s | 365 days | On unavailable |179180**Runbook Inventory:**181| Alert | Runbook | Owner | Last Verified |182|-------|---------|-------|---------------|183| High error rate | docs/runbooks/high-error-rate.md | Platform | 2024-01-01 |184```185186## QUALITY GATES187188- [ ] P95 and P99 latency tracked for all user-facing endpoints189- [ ] Error rate (5xx rate) tracked and alerting at > 1%190- [ ] Every log entry is structured JSON with at minimum: timestamp, level, service, message191- [ ] Correlation/trace IDs present in all logs for every request192- [ ] At least one SLO defined with error budget tracked on dashboard193- [ ] Every production alert has a linked runbook194- [ ] Runbook tested: follow it cold and confirm it resolves the described scenario195- [ ] PII not present in any log line (verified by audit sample)196- [ ] On-call rotation documented and first responder always identified197- [ ] Post-mortem template ready before first incident (not after)