Winston Logger Configuration

Set up a flexible logger with multiple transports for console and file outputs.

Logging is essential for debugging and monitoring. Winston is a popular Node.js library that provides a consistent interface for logging at different levels and to different destinations. This snippet configures a logger with console and rotating file transports. You can customise formats and log levels depending on your environment.

import { createLogger, format, transports } from "winston";
import "winston-daily-rotate-file";
 
export const logger = createLogger({
  level: process.env.NODE_ENV === "production" ? "info" : "debug",
  format: format.combine(
    format.timestamp(),
    format.printf(
      ({ level, message, timestamp }) => `${timestamp} [${level}]: ${message}`
    )
  ),
  transports: [
    new transports.Console({
      format: format.combine(format.colorize(), format.simple()),
    }),
    new transports.DailyRotateFile({
      dirname: "logs",
      filename: "%DATE%.log",
      datePattern: "YYYY-MM-DD",
      maxFiles: "14d",
    }),
  ],
});
 
// Usage: logger.info('Server started'); logger.error('Something went wrong');

This configuration writes human‑readable logs to the console and rotates log files daily, keeping them for two weeks. For production use, integrate with centralized logging services (e.g., Logstash, Datadog) via additional transports. Always adjust levels and formats based on your runtime environment.