Wyck
Wyck

Reputation: 11750

How to get node.js console.error and console.warn output in color

Is there a way to get node.js to output console.error and console.warn messages in color?

I'm hoping I can make all console.error messages red, console.warn messages yellow, and console.log messages the default color.

I looked around for a command line argument or environment variable option for node.exe, but I don't see anything. Perhaps colored console messages are something I have to opt into a different way?

I'd like a solution for Windows 10, in case that matters.

Upvotes: 10

Views: 11188

Answers (2)

SLaks
SLaks

Reputation: 887489

You can set the methods in console to wrapper functions that call the underlying methods (which you will need to store) but wrap them in colors.

Beware that you can also pass objects to console methods, which would be trickier to handle.

const actualError = console.error;

console.error = function(...args) {
  actualError(...args.map(a => typeof a === 'string' ? colorize(a) : a);
};

Upvotes: 2

VtoCorleone
VtoCorleone

Reputation: 17203

You can use the colors package.

https://www.npmjs.com/package/colors

Just use a wrapper for how you want them formatted

module.exports = {
  error: message => console.log(message.red),
  warn: message => console.log(message.yellow),
}

You could also use a logging library like pino that will colorize the log level in the message.

https://github.com/pinojs/pino

EDIT: To show basic logger file implementation

my-custom-logger.js

module.exports = {
  error: message => console.log(message.red),
  warn: message => console.log(message.yellow),
  info: message => console.log(message.green),
  debug: message => console.log(message.blue),
};

some-file.js

const logger = require('./my-custom-logger);

logger.error('Something went very wrong');
logger.warn('I am just a warning');
logger.info('This is informational');
logger.debug('Let us dig a little deeper');

What's nice about hiding it behind your own my-custom-logger.js file is that you can swap out the implementation behind the scenes without changing all of your code.

I would highly suggest looking deeper into pino, bunyan or winston as a logging framework. There are many benefits but the 2 biggest ones in my opinion are:

  1. The ability to raise/lower your log level to control how verbose your logging is
  2. Print out objects in JSON format and not using JSON.stringify(object)

Upvotes: 2

Related Questions