To Implement Winston Logger In Node Application

Posted By : Ranjan Mondal | 27-Feb-2018

Introduction: Winston a logging library is oftenly used in number of context such as express and node cli apps. It is used as logging timestamped entries to files.

Logging is one of the important things in our app. Managed and levels wise logging helps us to discover any problem very quickly.
Therefore we should setup loggers levels wise in our apps.

 

Setting up proper logging in Node.js applications can be bit overwhelming at first due many modules available through NPM. But  Some of the popular modules for logging in Node.js are -

There are many modules in node js for logging facility. Some very popular modules are Debug, Morgan, Log, Bunyan and Winston.

 

Problems with console.log()

We can not switch between the logs. It will always be printed wherever it is encountered.
We can not assign levels to logs. Eg. we may some logs in dev but not in productions.

 

Step 1: To install Winston and save it as a dependency in package.json. Just run command and it will install automatically.

     npm install --save winston   
        

Step 2: Add config.js file and add these configurations.

We usually run node app using NODE_ENV='prod' node app.js,   Where NODE_ENV = 'dev' or prod or stag. It will configure levels from env. 

    var getConfig = function() {
    var config = {};
    switch (process.env.NODE_ENV) {
        case constant.env.prod:
            config.loggerLevel = 'error';
            config.port = 4000;
            config.hostUrl = 'http://localhost'
            break;
        case constant.env.stag:
            config.loggerLevel = 'info';
            config.port = 4000;
            config.hostUrl = 'http://localhost'
            break;
        default:
            config.loggerLevel = 'debug';
            config.port = 4000;
            config.hostUrl = 'http://localhost'
            break;
    }
    config.endPoint = '';
    return config;
};

module.exports = getConfig;

        

Note : You can add logger level from following list.
{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 }

 

Step 3: Install winston daily rotate file module. It will create log file on daily basis. log-file name will be start from date and follow step 4.

   npm install --save winston-daily-rotate-file
        

Step 4:  Create logger.js file and add these lines. It will create directory and add log files on daily basis.

  var winston = require('winston');
const config = require('./config')();
const fs = require('fs');
const logDir = 'log';

// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir);
}

const tsFormat = () => (new Date()).toLocaleTimeString();

winston = new (winston.Logger)({
  transports: [
    // colorize the output to the console and add timestamp
    new (winston.transports.Console)({
      timestamp: tsFormat, colorize: true, level: config.loggerLevel
    }),

    // it will create log file named 'results.log' in log folder
     new (winston.transports.File)({
       filename: `${logDir}/results.log`,
       timestamp: tsFormat,
       level: config.loggerLevel
     }),
 
    // it will create date wise logfile like 2018-02-04-results.log
     new (require('winston-daily-rotate-file'))({
       filename: `${logDir}/-results.log`,
       timestamp: tsFormat,
       datePattern: 'yyyy-MM-dd',
       prepend: true,
       level: config.loggerLevel
     })
  ]
});
module.exports = winston;  
        

 

About Author

Author Image
Ranjan Mondal

Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..