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

  1. Install Winston: npm install winston.
  2. Create a logger instance with transports for console and file.
  3. Set log levels: error, warn, info, verbose, debug.
  4. Use structured logging: logger.info('User login', { userId: 123 });.
  5. 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.log can block the event loop under high load.
  • Uncaught exceptions should be logged before the process exits; handle them with process.on('uncaughtException').