Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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.

like image 865
Wyck Avatar asked May 30 '18 15:05

Wyck


2 Answers

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)
like image 186
VtoCorleone Avatar answered Oct 01 '22 19:10

VtoCorleone


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);
};
like image 30
SLaks Avatar answered Oct 01 '22 20:10

SLaks