Reza
Reza

Reputation: 19863

How to colorize parts of log message in winstonJs

I have the below code

const {
    colorize,
    combine,
    json,
    printf,
    simple,
    timestamp,
    errors,
    metadata
} = winston.format;

 private readonly consoleLogger = new winston.transports.Console({
        format: combine(
            errors({ stack: true }),
            metadata(),
            timestamp(),
            colorize({ all: true }),
            simple(),
            printf((info) => {
                const { level, message } = info;

                if (info?.metadata?.stackTrace) {
                    return `[${level}] ${message}\r\n${info.metadata.stackTrace}`;
                }
                return `[${level}] ${message}`;
            })
        )
    });

Based on docs and examples seems colorize will change the color of the whole line. I was wondering how can I colorize different part of string for example in my code I want timestamp, Level and message have different colors like image below

enter image description here

Upvotes: 0

Views: 1403

Answers (1)

Alucardik Anno
Alucardik Anno

Reputation: 41

The possible workaround could be adding colors to custom levels via:

winston.addColors({ yourLevelName: yourColor })

You can see possible color combinations here: https://github.com/winstonjs/winston#using-logging-levels

Then you can address your colors using Colorizer, returned by winston.format.colorize(), and inline them in your printf, for example, the following snippet

import winston from 'winston';

winston.addColors({ request: 'bold cyan magentaBG' });
const colorizer = winston.format.colorize();
const someColoredFormat = format.printf(({ level, timestamp, message, method }) =>
    `${timestamp} ${level}: ${colorizer.colorize('request', method)} ${message}`);


const someLogger = createLogger({
  level: 'info',
  format: format.combine(
    format.timestamp({
      format: 'YYYY-MM-DD hh:mm:ss',
    }),
    format.colorize({
      all: true,
    }),
    someColoredFormat
  ),
  transports: [new transports.Console()],
})

someLogger.info({
  method: 'GET',
  message: `-- some/api/route`
})

would produce the Output

I think this should help solve your case, however, I can't think of a more idiomatic way to do this, than mixing logging levels

Upvotes: 4

Related Questions