Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange symbols in log with winston

Initialization:

var winston = require('winston');
var logger = new (winston.Logger)({
    levels: {
        trace: 0,
        input: 1,
        verbose: 2,
        prompt: 3,
        debug: 4,
        info: 5,
        data: 6,
        help: 7,
        warn: 8,
        error: 9
    },
    colors: {
        trace: 'magenta',
        input: 'grey',
        verbose: 'cyan',
        prompt: 'grey',
        debug: 'blue',
        info: 'green',
        data: 'grey',
        help: 'cyan',
        warn: 'yellow',
        error: 'red'
    }
});

logger.add(winston.transports.Console, {
    level: 'error',
    prettyPrint: true,
    colorize: true,
    silent: false,
    timestamp: false,
    json: false
});

For example I call logger like this:

logger.info("isSandBox: " + isSandBox);

In my IDEA I see:

info: isSandBox: true

But when I've uploaded this script to Ubuntu server, I saw in the log:

^[[32minfo^[[39m: isSandBox: true

How can I fix it?

like image 624
Suvitruf - Andrei Apanasik Avatar asked Jan 16 '16 03:01

Suvitruf - Andrei Apanasik


2 Answers

The codes you're seeing are color code escapes. They are only useful when logging to a terminal/console, as they get interpreted by the terminal to change the text color. If the logs end up in a file, the codes are stored as-is, and are not really useful.

You can check if the output if a terminal, and only enable colorisation when it is:

logger.add(winston.transports.Console, {
    level       : 'error',
    prettyPrint : true,
    colorize    : process.stdout.isTTY,
    silent      : false,
    timestamp   : false,
    json        : false
});

More info on the isTTY flag here.

like image 98
robertklep Avatar answered Nov 18 '22 08:11

robertklep


In case you weren't able to solve this.. I was able to just now.

const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, colorize, printf } = format;

const myFormat = printf(info => {
  return `${info.timestamp} ${info.label} ${info.level}: ${info.message}`;
});

const logger = createLogger({
  format: combine(
    colorize(),
    label({ label: '[app-server]' }),
    timestamp(),
    myFormat
  ),
  transports: [new transports.Console()]
});

module.exports = logger;

The myFormat var is what allows it. None of the out of box formatters have the ability to translate the color code escapes.

like image 40
Eponym Avatar answered Nov 18 '22 09:11

Eponym