0
0
NodejsHow-ToBeginner · 4 min read

How to Use Winston for Logging in Node.js

Use winston by installing it via npm, then create a logger with transports like Console or File. Call logger methods such as logger.info() or logger.error() to log messages in your Node.js app.
📐

Syntax

Winston uses a logger object configured with transports that define where logs go (console, files, etc.). You call methods like logger.info() or logger.error() to log messages at different levels.

Each transport can have its own level and format.

javascript
import winston from 'winston';

const logger = winston.createLogger({
  level: 'info', // minimum level to log
  format: winston.format.json(), // log format
  transports: [
    new winston.transports.Console(), // logs to console
    new winston.transports.File({ filename: 'app.log' }) // logs to file
  ]
});

logger.info('This is an info message');
logger.error('This is an error message');
💻

Example

This example shows how to set up Winston to log info and error messages to the console and a file named app.log. It demonstrates creating a logger, setting log levels, and writing logs.

javascript
import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.printf(({ timestamp, level, message }) => {
      return `${timestamp} [${level.toUpperCase()}]: ${message}`;
    })
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ]
});

logger.info('Server started successfully');
logger.error('Failed to connect to database');
Output
2024-06-01T12:00:00.000Z [INFO]: Server started successfully 2024-06-01T12:00:00.001Z [ERROR]: Failed to connect to database
⚠️

Common Pitfalls

  • Not setting a transport causes no logs to appear.
  • Using console.log instead of Winston methods loses structured logging benefits.
  • Logging too much at a low level (like debug) in production can slow your app.
  • Forgetting to handle asynchronous logging when writing to files.

Always configure at least one transport and choose appropriate log levels.

javascript
import winston from 'winston';

// Wrong: No transports configured, no logs will show
const badLogger = winston.createLogger({ level: 'info' });
badLogger.info('This will not appear anywhere');

// Right: Add Console transport
const goodLogger = winston.createLogger({
  level: 'info',
  transports: [new winston.transports.Console()]
});
goodLogger.info('This will appear in the console');
Output
This will appear in the console
📊

Quick Reference

Here are key Winston logging methods and their typical use:

MethodDescription
logger.error(message)Logs error messages, highest priority
logger.warn(message)Logs warnings
logger.info(message)Logs informational messages
logger.verbose(message)Logs detailed info, less important
logger.debug(message)Logs debugging info, very detailed
logger.silly(message)Logs everything, lowest priority

Key Takeaways

Install Winston and create a logger with transports to output logs.
Use logger methods like info() and error() to log messages at different levels.
Always configure at least one transport, such as Console or File.
Choose log levels wisely to avoid performance issues in production.
Format logs for readability using Winston's format options.