can I change the color of log data in winston?

srujana picture srujana · Nov 6, 2017 · Viewed 11.4k times · Source

I happened to use bunyan to log the the data . I wanted the logs be printed with appropriate colors like errors in red , debug yellow .. etc; unfortunately I couldn't find anyways to do that . And now I would like to know if its possible with winston. Can I change the color of log data in winston ?

here is the code that I executed .

  var logger = require("winston-color");
  var winston = require('winston');  
  var util    = require('util');

  var logFilename = __dirname + '/logfile.log';

  var logger = new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ 
      filename: 'logfile.log',
      timestamp:true 
     }),
      new (winston.transports.File)({
      name: 'error-log',
      filename: 'error.log',
      level: 'error'
      }),

     new (winston.transports.File)({
     name: 'info-log',
     filename: 'info.log',
     level: 'info'
     }),
    ]
  });
  logger.info('Hello Winston info!');
  logger.debug('Hello Winston debug!');
  logger.warn('Hello Winston warn!');
  logger.info('Hello again distributed logs'); 
  logger.error('error1');
  logger.error('error2');

the output screen shot here

working code's output here here

Answer

codesnooker picture codesnooker · Nov 29, 2017

Yes you can. You can use the following code that I am using in my project.

logger/WinstonPlugin.js

/* jslint node: true */
/* jshint esversion: 6 */

'use strict';
const Winston = require('winston');
const logLevel = 'debug';

var logger;

(function createLogger() {

    logger = new(Winston.Logger)({
        transports: [
            new(Winston.transports.Console)({
                level: logLevel,
                colorize: true,
                timestamp: function () {
                    return (new Date()).toLocaleTimeString();
                },
                prettyPrint: true
            })
        ]
    });

    Winston.addColors({
        error: 'red',
        warn: 'yellow',
        info: 'cyan',
        debug: 'green'
    });
})();

module.exports = logger;

And anytime you needed the Winston in any your code file. You can access like below:

const Winston = require('logger/WinstonPlugin');
Winston.info('This is a info statement');
Winston.debug('This is a debug statement');
Winston.warn('This is a warning statement');
Winston.error('This is a error statement');

and you will see the colored output in the console.