Structured logs and metrics
Prerequisite: node-graceful-shutdown. Objective: Design redacted request log. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
Log an allowlisted event schema, such as route template, status, duration and a synthetic request id. Exclude credentials, request bodies and sensitive identifiers by default. Metrics use bounded label values, such as method or status class, rather than request IDs or raw URLs. A histogram records counts in ranges; percentiles estimated from it depend on bucket layout. Use a monotonic clock for durations and distinguish error counts from request counts. The following examples are local log/metric models, not exported telemetry.
Build an allowlisted log record
const request={id:'req-1',route:'/items/:id',status:200,durationMs:12,authorization:'synthetic-secret'};const {id,route,status,durationMs}=request;console.log(JSON.stringify({event:'request.complete',id,route,status,durationMs}));Expected output:
{"event":"request.complete","id":"req-1","route":"/items/:id","status":200,"durationMs":12}The input includes a deliberately fictional secret; only named output fields are emitted.
Aggregate counts by bounded status class
const counts=new Map();for(const status of [200,201,404,500,503]){const label=Math.floor(status/100)+'xx';counts.set(label,(counts.get(label)??0)+1);}console.log(JSON.stringify(Object.fromEntries(counts)));Expected output:
{"2xx":2,"4xx":1,"5xx":2}The metric has three label values, independent of how many distinct request IDs arrive.
Common mistakes
Do not spread an entire request object into a log or make every customer ID a metric label. Redaction at output is a fallback, not an excuse to collect secrets.
Practice
Design a bounded label set for four routes and explain why raw URLs would create unbounded cardinality.
Reference candidate: node-structured-logs-and-metrics-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/perf_hooks.html. Selected versioned documentation opened.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structured logs and metrics — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Which label is suitable for a request counter?
What should a structured log omit by default?
Which clock is appropriate for elapsed duration?