can I change the color of log data in winston?

Viewed 20461

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

7 Answers

If you look for a custom color schema you can write your own transporter like this

import winston from "winston";
import Transport from "winston-transport";

const Colors = {
    info: "\x1b[36m",
    error: "\x1b[31m",
    warn: "\x1b[33m",
    verbose: "\x1b[43m",
};

class SimpleConsoleTransport extends Transport {
    constructor() {
        super();
    }
    log = (info, callback) => {
        const { level, message, stack } = info;
        console.log(
                `${Colors[level]}${level}\t${message}\x1b[0m`,
                stack ? "\n" + stack : ""
            )
        if (callback) {
            callback();
        }
    };
}

then config your winston instance this way:

winston.configure({
            transports: [new SimpleConsoleTransport()],
        });

these are the whole list of colors you can use:

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"

I followed this answer and got it working with colors

new winston.transports.Console({
  format: winston.format.combine(
            winston.format.colorize(),
            winston.format.simple()
          )
});

All might be right but i have one simple solution for that

create a file called winston.js and put below code

const winston = require('winston');
const logger = winston.createLogger({
    transports: [
        new winston.transports.Console({
            format: winston.format.combine(
                winston.format.colorize(),
                winston.format.simple()
            )
        })
    ]
});
global.logger = logger;

Now import this file to any file you want (Probably index.js).

require('./config/winston');
logger.error("Oops, It's Error");
logger.info("This is info Msg");
logger.warn("Something went wrong")

Emoji

You can use colors for text as others mentioned in their answers.

But you can use emojis instead! for example, you can use⚠️ for warning messages and for error messages. (Even without the logger! But you can also wrap it inside the logger for access control purpose)

Or simply use these notebooks as a color:

console.log(': error message');
console.log(': warning message');
console.log(': ok status message');
console.log(': action message');
console.log(': canceled status message');
console.log(': Or anything you like and want to recognize immediately by color');

Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

Also, it does not depend on any framework and you can use it anywhere freely.

But Linux default emoji font is not colorful by default and you may want to make them colorful, first.

Related