winston custom logs color

3.8k Views Asked by At

I wanna create custom log levels. Creation is correct and I can use them in the future, but messages are not colorized when I use custom levels. As I can see - colors are added before levels and that's why I can't use colors for custom levels. My code is bellow and when I use warn or custom - it crashed with error:

TypeError: colors[Colorizer.allColors[lookup]] is not a function

Also code of calling:

const Winston = require('./logger');
Winston.error('1 This is a info statement');
Winston.data('2 This is a warning statement');
Winston.info('3 This is a warning statement');
Winston.debug('4 This is a error statement');
Winston.verbose('6 This is a warning statement');
Winston.silly('7 This is a error statement');
Winston.warn('5 This is a debug statement');
Winston.custom('8 This is a error statement');

and logger.js

const winston = require('winston');
const colorizer = winston.format.colorize();
const {
  combine, timestamp, printf, simple,
} = winston.format;

const myCustomLevels = {
  levels: {
    error: 0,
    warn: 1,
    data: 2,
    info: 3,
    debug: 4,
    verbose: 5,
    silly: 6,
    custom: 7,
  },
  colors: {
    error: 'red',
    warn: 'orange',
    data: 'grey',
    info: 'green',
    debug: 'yellow',
    verbose: 'cyan',
    silly: 'magenta',
    custom: 'blue',
  },
};

colorizer.addColors(myCustomLevels.colors);

const logger = winston.createLogger({
  colorize: true,
  prettyPrint: true,
  level: 'custom',
  levels: myCustomLevels.levels,
  format: combine(
    simple(),
    printf(
      (msg) => {
        return colorizer.colorize(
          msg.level,
          `${msg.level} - ${msg.message}`,
        );
      },
    ),
    timestamp(),
  ),
  transports: [
    new winston.transports.Console(),
  ],
});

module.exports = logger;

How I can use colorize with custom levels?

1

There are 1 best solutions below

0
On

Usnig colorize:true will break your custom format, if you want to colorize all your log text you can do it manually like this:

const { combine, timestamp, label, printf } = winston.format;
const color = {
'info': "\x1b[36m",
'error': "\x1b[31m",
'warn': "\x1b[33m"
.
.
.
};
const myFormat = printf(({ level, message, label, timestamp }) => {
return `${level}: ${color[level] || ''} ${label} || ${timestamp} || ${message}\x1b[0m `;
});

then use this in createLogger function:

levels: myLevels,
format: combine(
winston.format.prettyPrint(),
winston.format.metadata(),
winston.format.json(),
label({ label }),
timestamp(),
myFormat
),
.
.
.