Advanced Node.js Interview QuestionsAdvancedScenario
Node.js · Question 97
How would you implement structured logging in a Node.js API?
Direct answer
Use pino (Fastify default) or winston with JSON lines — log level, msg, reqId, userId, duration; redact secrets; stdout for Docker; correlate request/response in hooks; avoid console.log in production.
Scenario: debug slow GET /interviews/topics/:slug in production using searchable JSON logs (Q32, Q76).
| Field | Purpose |
|---|---|
| level | info/warn/error filtering |
| reqId | Trace one request across services |
| req.method + url | Identify route |
| responseTime | Latency SLO monitoring |
| err.stack | Server-side only on 5xx |
scenario-pino.mjs
import pino from "pino";
const logger = pino({
level: process.env.LOG_LEVEL ?? "info",
redact: ["req.headers.authorization", "req.headers.cookie"],
});
fastify.addHook("onResponse", async (req, reply) => {
req.log.info({
reqId: req.id,
method: req.method,
url: req.url,
statusCode: reply.statusCode,
responseTime: reply.elapsedTime,
}, "request completed");
});