How to implement logging in production Node.js applications
· Category: Node.js
Short answer
Use a dedicated logging library like Winston or Pino instead of console.log to support log levels, structured formats, and multiple transports.
Steps
- Install Winston:
npm install winston. - Create a logger instance with transports for console and file.
- Set log levels:
error,warn,info,verbose,debug. - Use structured logging:
logger.info('User login', { userId: 123 });. - Rotate log files to prevent disk space exhaustion.
Tips
- Use JSON formatting in production so log aggregation systems can parse fields automatically.
- Redact sensitive fields like passwords and tokens before logging.
Common issues
- Synchronous file logging with
console.logcan block the event loop under high load. - Uncaught exceptions should be logged before the process exits; handle them with
process.on('uncaughtException').