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.
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:
JSON.stringify(object)
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With