Emit machine-readable JSON logs with severity, request correlation, durations, safe error serialization, and automatic redaction of credentials.
What you will build
This tutorial produces a working, verifiable result rather than a command list. Read each command before running it, keep configuration in version control without secrets, and record the versions used for repeatable deployment.
1. Prepare the project
npm install pino pino-http
export LOG_LEVEL=info
Run preparation commands as an unprivileged application user unless a command explicitly requires sudo. A clean working tree and lockfile make rollback much easier.
2. Implement the solution
import express from 'express'; import pino from 'pino'; import pinoHttp from 'pino-http'; import {randomUUID} from 'node:crypto';
const logger=pino({level:process.env.LOG_LEVEL??'info',redact:['req.headers.authorization','req.headers.cookie','password','token']});
const app=express(); app.use(pinoHttp({logger,genReqId:req=>req.headers['x-request-id']??randomUUID()}));
app.get('/healthz',(req,res)=>{req.log.info({component:'health'},'health check');res.json({status:'ok'});});
app.listen(3000,()=>logger.info({port:3000},'server started'));
Save the example in the filename indicated by its comment or surrounding instructions. Treat it as a minimal baseline: production applications should separate transport, business logic, persistence, and configuration into testable modules.
3. Verify end to end
node server.js | tee app.log
curl -H 'x-request-id: demo-123' http://127.0.0.1:3000/healthz
jq -c 'select(.reqId=="demo-123")' app.log
Verification should cover both process state and a real request or data operation. A process that is merely running is not necessarily ready to serve traffic.
4. Troubleshooting and production notes
Write logs to stdout in containers and let the platform collect them. Redact secrets at the logger, not by developer convention. Control high-cardinality fields, sample noisy success logs, retain errors, and do not treat logging as metrics or tracing.
Production checklist
- The supported Node.js LTS version and dependency lockfile are recorded.
- Configuration is validated at startup and secrets are stored outside source control.
- Input limits, authentication, authorization, timeouts, and error boundaries are explicit.
- Logs identify a request without exposing credentials or personal data.
- Health checks, graceful termination, resource limits, backup, and rollback have been tested.
Reference: official topic documentation. For production version selection, use a supported LTS line from the Node.js release schedule.