18

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

srujana
  • 501
  • 2
  • 6
  • 13
  • There's [winston-color](https://www.npmjs.com/package/winston-color) package which does the job? – zc246 Nov 06 '17 at 09:50
  • didn't work !! it shows the out put in plain white ! – srujana Nov 06 '17 at 10:47
  • By looking at the code, it feels like you've redefined `logger` back to default one? – zc246 Nov 06 '17 at 11:06
  • redefining logger ? can you please make me clear on it ? If observed output screen shot it didn't print debug statement . How can I get out of it ? – srujana Nov 06 '17 at 11:09
  • I understood what the problem was ! but this also works the same way as bunyan . It only shows the log levels in colors but not the log data . – srujana Nov 06 '17 at 11:33

7 Answers7

12

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.

bearbyt3z
  • 75
  • 1
  • 6
codesnooker
  • 1,191
  • 10
  • 19
11

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"
6

I followed this answer and got it working with colors

new winston.transports.Console({
  format: winston.format.combine(
            winston.format.colorize(),
            winston.format.simple()
          )
});
Shonubi Korede
  • 541
  • 6
  • 4
1

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")
Renish Gotecha
  • 2,232
  • 22
  • 21
0

I have not tried this. But according to this you use color for logs. enter link description here

Ajantha Bandara
  • 1,473
  • 15
  • 36
  • Thank you for your quick response . I tried it too . But I need the entire log data of certain level be of a color . – srujana Nov 06 '17 at 09:41
0

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.

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
-1

Tried your fix; Winston doesn't pay attention to any of the color settings.

jtiscione
  • 1,131
  • 8
  • 13