Full answer
Design checklist:
- Format and destination: JSON lines on stdout. No log files, rotation or shipping inside the app; the platform does that.
- Fields: timestamp (ISO or epoch), level, message (a constant text), service and version, environment, and event fields (userId, route, durationMs, statusCode). Use the same field names across services.
- Correlation: a request id (and trace id) on every line of a request. AsyncLocalStorage can carry it without passing a logger through every function.
- Levels: error means someone should look at it, warn means unexpected but handled, info is business events and one line per request, debug is for investigation and is off by default.
- Errors: log the type, message, stack and the cause chain, plus context. Log an error once, at the place that handles it, not at every layer it passes through.
- Redaction: remove passwords, tokens, authorization headers, card numbers and personal data. Use a key list and also avoid logging whole request or response bodies.
- Volume and cost: sample high-volume low-value lines (for example log 1 in 100 debug lines), cap field sizes, and avoid logging inside tight loops.
- Performance: serialize cheaply, write asynchronously, and never await the logger in the request path. A logging failure must not break the request.
- Retention and access: decide how long logs are kept and who may read them, since logs often contain personal data.
The code below shows the core of such a logger in a few lines: level filter, redaction, error serialization with cause, and sampling, with an injected clock and random function for repeatable output.
const LEVELS = { debug: 20, info: 30, warn: 40, error: 50 };
const SECRET = /password|token|secret|authorization|card/i;
function serializeError(err) {
return {
type: err.name,
message: err.message,
code: err.code,
cause: err.cause ? serializeError(err.cause) : undefined,
};
}
function redact(value, depth = 0) {
if (value instanceof Error) return serializeError(value);
if (!value || typeof value !== 'object' || depth > 4) return value;
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET.test(k) ? '[redacted]' : redact(v, depth + 1)]));
}
function createLogger({ level = 'info', bindings = {}, sampleDebug = 1, now = () => new Date().toISOString(), random = Math.random, write = (line) => console.log(line) } = {}) {
const make = (extra) => {
const logAt = (name) => (fields, message) => {
if (LEVELS[name] < LEVELS[level]) return;
if (name === 'debug' && random() >= sampleDebug) return; // sampling
try {
write(JSON.stringify({ time: now(), level: name, msg: message, ...extra, ...redact(fields) }));
} catch {
/* logging must never break the request */
}
};
return {
debug: logAt('debug'), info: logAt('info'), warn: logAt('warn'), error: logAt('error'),
child: (more) => make({ ...extra, ...more }),
};
};
return make(bindings);
}
const log = createLogger({
level: 'debug',
bindings: { service: 'marks-api', version: '1.4.2' },
sampleDebug: 0.5,
now: () => '2026-12-04T10:00:00.000Z',
random: (() => { let i = 0; return () => [0.1, 0.9, 0.3, 0.7][i++ % 4]; })(), // repeatable
});
const requestLog = log.child({ requestId: 'req-7' });
requestLog.info({ method: 'POST', route: '/marks', status: 201, durationMs: 18 }, 'request finished');
requestLog.warn({ body: { name: 'Asha', password: 'secret123' } }, 'payload contained a password field');
const root = new Error('connection refused', { cause: undefined });
root.code = 'ECONNREFUSED';
requestLog.error({ err: new Error('could not save marks', { cause: root }) }, 'save failed');
for (let i = 1; i <= 4; i++) requestLog.debug({ attempt: i }, 'cache lookup'); // sampled: keeps about halfThe injected random function makes the sampling repeatable. In the output, two of the four debug lines are dropped. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): {"time":"2026-12-04T10:00:00.000Z","level":"info","msg":"request finished","service":"marks-api","version":"1.4.2","requestId":"req-7","method":"POST","route":"/marks","status":201,"durationMs":18} {"time":"2026-12-04T10:00:00.000Z","level":"warn","msg":"payload contained a password field","service":"marks-api","version":"1.4.2","requestId":"req-7","body":{"name":"Asha","password":"[redacted]"}} {"time":"2026-12-04T10:00:00.000Z","level":"error","msg":"save failed","service":"marks-api","version":"1.4.2","requestId":"req-7","err":{"type":"Error","message":"could not save marks","cause":{"type":"Error","message":"connection refused","code":"ECONNREFUSED"}}} {"time":"2026-12-04T10:00:00.000Z","level":"debug","msg":"cache lookup","service":"marks-api","version":"1.4.2","requestId":"req-7","attempt":1} {"time":"2026-12-04T10:00:00.000Z","level":"debug","msg":"cache lookup","service":"marks-api","version":"1.4.2","requestId":"req-7","attempt":3}
Key points
- Structured JSON lines on stdout, with a constant message and fields.
- Correlation ids link all lines of a request.
- Redact secrets and avoid logging whole bodies.
- Log each error once, with its cause chain.
- Sample noisy lines and never block the request.
Common mistakes
- Logging the same error at every layer, so one failure creates many lines.
- Putting secrets or whole request bodies into logs.
- Letting the logger throw on circular objects and crash the request.
- Writing logs to local files in a container.
Follow-ups
- How would AsyncLocalStorage give every log line a request id?
- How do you decide log retention?
- What is the difference between logs, metrics and traces?
Tips
- Say 'one event, one line, constant message'.
- Link correlation ids to AsyncLocalStorage.
- Mention cost: logs are expensive at scale.