Express by Examples

Winston Logger

To log info messages, errors etc use 'winston' npm module.

Installation

$ npm install --save winston

 

Integration

Simplest example with terminal transportation.

var winston = require('winston');

 

/* with enrouten middleware */
module.exports = function (router) {

  //http://localhost:3000/tests/winston
  router.get('/', function (req, res) {
    winston.log('error', 'This error message will appear in terminal !');

    res.send('Winston error initialized!');
  });

};

 

 

 If we want to log into file and not to show in terminal:

//winston logger
var winston = require('winston');
var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
    new (winston.transports.File)({ filename: 'mylog.log' })
  ]
});

 
module.exports = function (router) {

  //http://localhost:3000/tests/winston
  router.get('/file', function (req, res) {
    
    // console.log(JSON.stringify(logger, null, 2));

    logger.remove(winston.transports.Console);
    logger.log('error', 'This error message will be added as line in file !');

    res.send('Winston error initialized! Will appear in file.');
  });

};

 

 To put certain log level in different files use:

//each log level in separate file
var logger2 = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      name: 'info-file',
      filename: 'filelog-info.log',
      level: 'info'
    }),
    new (winston.transports.File)({
      name: 'error-file',
      filename: 'filelog-error.log',
      level: 'error',
      colorize: false,
      timestamp: true,
      json: true,
      handleExceptions: false
    })
  ]
});

 

module.exports = function (router) {

  //http://localhost:3000/tests/winston/difffile
  //logging different errors to diferent
  router.get('/difffile', function (req, res) {

    logger2.log('error', 'This error message will be appended in filelog-error.log!');
    logger2.log('info', 'This info message will be appended in filelog-info.log!');

    res.send('Winston logs initialized! Will appear in two different files.');
  });

};

 

 

 Logging levels

silly , debug , verbose , info , warn , error

 logger.log('silly', "127.0.0.1 - there's no place like home");
  logger.log('debug', "127.0.0.1 - there's no place like home");
  logger.log('verbose', "127.0.0.1 - there's no place like home");
  logger.log('info', "127.0.0.1 - there's no place like home");
  logger.log('warn', "127.0.0.1 - there's no place like home");
  logger.log('error', "127.0.0.1 - there's no place like home");
  logger.info("127.0.0.1 - there's no place like home");
  logger.warn("127.0.0.1 - there's no place like home");
  logger.error("127.0.0.1 - there's no place like home");