Logging
When something breaks in production, logs are often all you have. Good logs answer: which request, what happened, how long did it take, who was affected — without leaking passwords or tokens.
What to log
| Event | Level | Example fields |
|---|---|---|
| every finished request | info |
method, path, status, duration, request id |
| expected client errors (4xx) | info / warn |
status, reason |
| unexpected errors (5xx) | error |
error message, stack, request id |
| startup / shutdown | info |
port, version, environment |
| detailed internals | debug |
queries, cache hits (off in production) |
Log levels let you change verbosity without touching code: production usually runs at info, development at debug.
Structured logs: JSON lines
console.log('User ' + id + ' failed') is fine for humans, but impossible to search across millions of lines. Structured logging writes one JSON object per line, so log tools (Grafana Loki, Elasticsearch, CloudWatch, Datadog) can filter by any field:
const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
function createLogger({ level = 'info', base = {}, write = console.log } = {}) {
const min = LEVELS[level];
const log = (lvl) => (msg, fields = {}) => {
if (LEVELS[lvl] < min) return;
write(JSON.stringify({ level: lvl, msg, ...base, ...fields }));
};
return {
debug: log('debug'), info: log('info'), warn: log('warn'), error: log('error'),
child: (extra) => createLogger({ level, base: { ...base, ...extra }, write }),
};
}
const logger = createLogger({ level: 'info', base: { service: 'notes-api' } });
logger.debug('cache miss', { key: 'user:1' }); // below the level: dropped
logger.info('server started', { port: 3000 });
const reqLog = logger.child({ requestId: 'req-42' });
reqLog.warn('slow query', { ms: 812 });
reqLog.error('payment failed', { provider: 'acme', code: 'card_declined' });{"level":"info","msg":"server started","service":"notes-api","port":3000}
{"level":"warn","msg":"slow query","service":"notes-api","requestId":"req-42","ms":812}
{"level":"error","msg":"payment failed","service":"notes-api","requestId":"req-42","provider":"acme","code":"card_declined"}
A child logger carries context (here the request id) into every line without repeating it.
Note: Real log lines also include a timestamp (
time). It's left out here so the output is reproducible. In production you'd use pino (very fast JSON logger) or winston.
Request logging middleware
An access-log middleware records each request when the response finishes. It also assigns a request id, sends it back in a header, and makes a child logger available to handlers through req.log:
const express = require('express');
const lines = [];
const logger = {
child: (ctx) => ({
info: (msg, f = {}) => lines.push(JSON.stringify({ level: 'info', msg, ...ctx, ...f })),
error: (msg, f = {}) => lines.push(JSON.stringify({ level: 'error', msg, ...ctx, ...f })),
}),
};
let seq = 0;
function requestLogger(req, res, next) {
const requestId = req.get('X-Request-Id') ?? `req-${++seq}`;
res.set('X-Request-Id', requestId);
req.log = logger.child({ requestId });
res.on('finish', () => {
req.log.info('request completed', { method: req.method, path: req.originalUrl, status: res.statusCode });
});
next();
}
const app = express();
app.use(requestLogger);
app.get('/notes', (req, res) => res.json([]));
app.get('/fail', () => { throw new Error('database unreachable'); });
app.use((err, req, res, next) => {
req.log.error('unhandled error', { error: err.message });
res.status(500).json({ error: 'Internal Server Error' });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
await fetch(base + '/notes');
await fetch(base + '/fail');
await fetch(base + '/notes?page=2', { headers: { 'X-Request-Id': 'from-gateway-7' } });
server.close();
console.log(lines.join('\n'));
});{"level":"info","msg":"request completed","requestId":"req-1","method":"GET","path":"/notes","status":200}
{"level":"error","msg":"unhandled error","requestId":"req-2","error":"database unreachable"}
{"level":"info","msg":"request completed","requestId":"req-2","method":"GET","path":"/fail","status":500}
{"level":"info","msg":"request completed","requestId":"from-gateway-7","method":"GET","path":"/notes?page=2","status":200}
Reusing an incoming X-Request-Id lets you trace one user action through a gateway and several services.
Tip: Also log the duration. Use
process.hrtime.bigint()(orperformance.now()) at the start and in thefinishlistener — and for real request ids usecrypto.randomUUID().
Never log secrets
Passwords, tokens, cookies and full card numbers must never reach your logs — logs are copied to many systems and kept for months. Redact sensitive keys before writing:
const SENSITIVE = ['password', 'token', 'authorization', 'cookie', 'cardnumber'];
function redact(value: unknown): unknown {
if (Array.isArray(value)) return value.map(redact);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, SENSITIVE.includes(k.toLowerCase()) ? '[REDACTED]' : redact(v)]),
);
}
return value;
}
console.log(redact({
email: 'ana@example.com',
password: 'hunter2',
headers: { Authorization: 'Bearer abc.def', accept: 'application/json' },
payment: { cardNumber: '4111111111111111', amount: 25 },
}));{
email: 'ana@example.com',
password: '[REDACTED]',
headers: { Authorization: '[REDACTED]', accept: 'application/json' },
payment: { cardNumber: '[REDACTED]', amount: 25 }
}
pino has this built in: pino({ redact: ['req.headers.authorization', '*.password'] }).
Using pino in a real app
const pino = require('pino');
const pinoHttp = require('pino-http');
const logger = pino({ level: process.env.LOG_LEVEL ?? 'info' });
app.use(pinoHttp({ logger })); // adds req.log and logs every request
app.get('/notes', (req, res) => {
req.log.debug({ userId: req.user?.id }, 'listing notes');
res.json([]);
});Write logs to stdout and let the platform (Docker, systemd, Kubernetes) collect them. Don't manage log files and rotation inside your app.
Test yourself
Why prefer JSON log lines over free-form text?
- They are shorter
- Log tools can filter and aggregate by any field
- JSON can't contain errors
- Express requires JSON logs
When should an access-log middleware write its line to include the final status code?
- Before calling next()
- In the response's
finishevent - In
app.listen - When the next request arrives
Which of these should never appear in logs?
- HTTP status codes
- Request ids
- Bearer tokens and passwords
- Response durations