Logging and monitoring
Overview
When something goes wrong in production, you can’t attach a debugger or add a console.log and refresh. Logs and metrics are how you see inside your running application. Good logging is the difference between “users say checkout is broken, no idea why” and “request 7f3a… failed at 14:02 because the payment provider timed out after 10 s”.
Why console.log isn’t enough
console.log('User created', user.id) produces text meant for humans. In production, logs from many instances are collected into a system like Grafana Loki, Datadog, Elastic or CloudWatch, where you search and filter them. That works far better with structured logs: one JSON object per line, with named fields.
With fields, you can ask “show every 500 on /api/v1/orders in the last hour” or “graph p95 responseTime per route” — impossible with free-form text.
pino
pino is the most popular Node.js logger: it’s very fast and logs JSON by default.
npm install pino pino-http
npm install --save-dev pino-pretty// src/logger.js
import pino from 'pino';
export const logger = pino({
level: process.env.LOG_LEVEL ?? 'info',
redact: ['req.headers.authorization', 'req.headers.cookie', '*.password'],
transport: process.env.NODE_ENV === 'development'
? { target: 'pino-pretty' } // colourful, readable output while developing
: undefined, // plain JSON in production
});logger.info('Server started');
logger.info({ port: 3000 }, 'Listening'); // fields first, message second
logger.warn({ userId, attempts }, 'Too many login attempts');
logger.error({ err }, 'Failed to send email'); // `err` is serialised with message and stackOutput (one line, shown wrapped):
{"level":30,"time":1764750000000,"pid":4821,"hostname":"api-1","port":3000,"msg":"Listening"}Log to stdout, not to files. Docker, Kubernetes and every hosting platform capture stdout and ship it wherever you configure. Writing your own log files means handling rotation, disk space and collection yourself.
Log levels
| Level | Use for | Example |
|---|---|---|
fatal |
the app is about to crash | can’t connect to the database at startup |
error |
an operation failed and needs attention | unexpected exception in a route |
warn |
something unusual, but handled | retrying a flaky API, deprecated endpoint used |
info |
important normal events | server started, user signed up, job finished |
debug |
detail useful while investigating | SQL queries, cache hits and misses |
trace |
extremely detailed | full payloads |
Run production at info and switch to debug temporarily (via LOG_LEVEL) while investigating. Don’t log every request body at info — it’s noisy and may leak personal data.
Request logging and request IDs
pino-http logs one line per request — method, URL, status code and response time — and gives each request a child logger, req.log, that automatically includes the request’s ID:
import { randomUUID } from 'node:crypto';
import { pinoHttp } from 'pino-http';
import { logger } from './logger.js';
app.use(pinoHttp({
logger,
genReqId(req, res) {
const id = req.headers['x-request-id'] ?? randomUUID();
res.setHeader('x-request-id', id);
return id;
},
customLogLevel(req, res, err) {
if (err || res.statusCode >= 500) return 'error';
if (res.statusCode >= 400) return 'warn';
return 'info';
},
}));Now use req.log inside routes and services:
req.log.info({ courseId }, 'Enrolling student');Every line for that request carries the same reqId. When a user reports a problem, the x-request-id header in their response lets you find every log line for their request — across your middleware, services, and even other services if you forward the header on outgoing calls.
Update the error handler from Error handling in Express to log through the request:
export function errorHandler(err, req, res, next) {
const status = err.status ?? 500;
if (status >= 500) req.log.error({ err }, 'Unhandled error');
res.status(status).json({ error: status >= 500 ? 'Internal server error' : err.message });
}What not to log
Logs are copied, retained and read by many people. Never log:
- passwords, tokens, API keys, session IDs,
AuthorizationorCookieheaders, - full card numbers or other payment data,
- unnecessary personal data (full request bodies with names, addresses, health information).
pino’s redact option replaces listed paths with [Redacted], so a careless logger.info({ req }) can’t leak them.
Monitoring: metrics and alerts
Logs tell you about individual events. Metrics are numbers over time that tell you how the whole system is doing. For an HTTP API, start with the RED method, per route:
- Rate — requests per second,
- Errors — the share of requests that fail (5xx),
- Duration — latency percentiles (p50, p95, p99).
Add Node-specific and dependency metrics:
- event-loop delay (see Profiling and performance),
- memory (
heapUsed,rss) and CPU, - database pool usage and query time, cache hit rate,
- job queue length and failed jobs.
prom-client exposes these in Prometheus format at a /metrics endpoint; OpenTelemetry collects metrics and distributed traces and can send them to almost any vendor. Many platforms also give you request metrics out of the box.
Alerting
Alert on symptoms users feel, not on every internal wobble:
- error rate above 2% for 5 minutes,
- p95 latency above 1 s for 10 minutes,
- health check failing,
- job queue backlog growing for 15 minutes.
Each alert should be actionable — if nobody needs to do anything, it’s noise, and noisy alerts get ignored.
Error tracking
A tool such as Sentry captures exceptions with stack traces, the request that caused them, and how many users were affected, and groups repeats together. It complements logs: logs tell the story; error tracking tells you which bugs to fix first.
Test your observability before you need it. Trigger an error in staging and check that you can find its log line by request ID, see it in error tracking, and that the alert fires.
Request logging with pino
Create src/logger.js exporting a pino logger whose level comes from LOG_LEVEL (default info), that redacts req.headers.authorization and req.headers.cookie, and pretty-prints only when NODE_ENV is development. Then add pino-http to the Express app so every request is logged with a request ID taken from an incoming x-request-id header or generated with crypto.randomUUID(), and echoed back in the response.
// src/logger.js
import pino from 'pino';
export const logger = // your code here
// src/app.js
import { pinoHttp } from 'pino-http';// src/logger.js
import pino from 'pino';
export const logger = pino({
level: process.env.LOG_LEVEL ?? 'info',
redact: ['req.headers.authorization', 'req.headers.cookie'],
transport: process.env.NODE_ENV === 'development' ? { target: 'pino-pretty' } : undefined,
});
// src/app.js
import { randomUUID } from 'node:crypto';
import { pinoHttp } from 'pino-http';
import { logger } from './logger.js';
app.use(pinoHttp({
logger,
genReqId(req, res) {
const id = req.headers['x-request-id'] ?? randomUUID();
res.setHeader('x-request-id', id);
return id;
},
}));
app.get('/api/v1/courses/:id', async (req, res) => {
req.log.info({ courseId: req.params.id }, 'loading course');
// …
});Summary
- Log JSON, one object per line, to stdout — let the platform collect and ship it.
- pino is fast and structured; pino-http logs every request and gives you
req.log. - A request ID on every line lets you follow one request through all its logs.
- Use levels deliberately, and redact secrets and personal data.
- Monitor rate, errors and duration per route, plus event-loop delay, memory and dependencies — and alert on symptoms users feel.