🟢 Node.js Intermediate

How do you implement logging in a Node.js application?

Answer

Effective logging is critical for debugging and monitoring Node.js production applications. console.log() is acceptable for development but insufficient for production. Production logging requirements: structured logs (JSON format for log aggregation), log levels (error, warn, info, debug), timestamps, contextual data, and transport options (file, stdout, external services). Libraries: (1) Winston — most popular, supports multiple transports, log rotation, custom formatters: const logger = winston.createLogger({ level: "info", format: winston.format.json(), transports: [new winston.transports.Console(), new winston.transports.File({ filename: "error.log", level: "error" })] });; (2) Pino — extremely fast (10x faster than Winston due to minimal sync operations), JSON output by default, used by Fastify; (3) Morgan — HTTP request logger middleware for Express. Best practices: log at the appropriate level, never log sensitive data (passwords, tokens, PII), use correlation IDs to trace requests across services, and send logs to centralized systems (Datadog, ELK Stack, CloudWatch) in production.