0
0
Expressframework~5 mins

Winston for application logging in Express

Choose your learning style9 modes available
Introduction

Winston helps you keep track of what your app is doing by saving messages about events. This makes it easier to find and fix problems.

You want to record errors happening in your app to fix them later.
You need to save info about user actions for security or analysis.
You want to keep logs in files instead of just showing them on the screen.
You want to separate logs by importance, like errors vs. normal info.
You want to send logs to different places, like files and the console.
Syntax
Express
const winston = require('winston');

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

logger.info('Message here');

level sets the minimum importance of messages to save.

transports are where logs go, like console or files.

Examples
This example logs only error messages to the console.
Express
const logger = winston.createLogger({
  level: 'error',
  transports: [new winston.transports.Console()]
});

logger.error('This is an error message');
This example saves info messages in a simple text format to a file.
Express
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

logger.info('App started');
This example shows colored debug messages in the console for easier reading.
Express
const logger = winston.createLogger({
  level: 'debug',
  format: winston.format.combine(
    winston.format.colorize(),
    winston.format.simple()
  ),
  transports: [new winston.transports.Console()]
});

logger.debug('Debugging info');
Sample Program

This Express app uses Winston to log when the server starts and when someone visits the home page. Logs go to both the console and a file named app.log.

Express
const express = require('express');
const winston = require('winston');

const app = express();

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'app.log' })
  ]
});

app.get('/', (req, res) => {
  logger.info('Home page was visited');
  res.send('Hello World!');
});

app.listen(3000, () => {
  logger.info('Server started on port 3000');
});
OutputSuccess
Important Notes

Winston timestamps logs automatically if you add the timestamp format.

You can add more transports to send logs to places like remote servers.

Use different log levels to control what messages get saved.

Summary

Winston helps save messages about your app's actions and errors.

You can send logs to the console, files, or other places.

Setting log levels helps you focus on important messages.