What is winston and why is it needed?
Winston is the most popular logging library in the Node.js environment. It provides a simple, universal API that allows you to write logs with different severity levels, format them, and send them to different places (console, files, databases, external services). Unlike simple console.log, winston gives you full control over logging: you can configure log rotation by size or date, filter messages by level (info, warn, error, debug), add metadata (time, request ID), and even use multiple transports simultaneously. It is an indispensable tool for monitoring, debugging, and auditing in production applications.
Installation
Install winston via npm or yarn:
npm install winston# oryarn add winstonMain Features
- Logging levels: error, warn, info, http, verbose, debug, silly.
- Transports: Console, File, HTTP, Stream, and custom ones.
- Formats: JSON, plain text, timestamps, colored output.
- Combining multiple transports: for example, errors to a file, and info to the console.
- Custom transports and formats: can be integrated with Logstash, Sentry, Papertrail, and others.
- Log rotation: via the additional winston-daily-rotate-file module.
- Exceptions and unhandled rejections: automatic interception of unhandled errors.
Code Example in JavaScript (Node.js)
const winston = require('winston');
// Create a loggerconst logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.json() ), transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.simple() ) }), new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }) ]});
// Usagelogger.info('Server started on port 3000');logger.warn('Insufficient memory', { memoryUsage: process.memoryUsage() });try { throw new Error('Something broke');} catch (err) { logger.error('Error processing request', { error: err.message, stack: err.stack });}When to Use
Winston is ideal for any Node.js projects that require structured logging: web servers (Express, Koa), microservices, CLI utilities, bots, ETL processes. It is especially useful in a production environment where you need to centrally collect logs, analyze errors, and quickly find problems. If your project uses TypeScript, winston has full type support.
Alternatives: pino (faster, smaller), log4js (configuration via XML/JSON), bunyan (JSON logs). But winston remains the most flexible and widespread solution.