As you’re working with NodeJS more and more, you’ll soon find yourself in a position to put in more logging messages than ever before. Especially, when your server encounters a number of, say, error handling exceptions, such that you want to divide your continuous stream of logger messages into the following:
- Critical messages
- Info messages
- Warning errors
- Debugging errors, etc
And our best logging friend is console.log
usually comes to the rescue for the all the above-mentioned things. But sometimes, you just wish there’s a better way to preformat and categorise them differently when they get spat out in the terminal screen, as you go.
That’s where Chalk comes in.
It’s available as an npm module. So you can simply use it like so.
const chalk = require(‘chalk’);
Store console.log
as a separate module.
const chalk = require('chalk');
const log = console.log;
Next, you define your logging colour classification for your needs.
const error = chalk.bold.red
const info = chalk.bold.blue
const warn = chalk.bold.yellow
const debug = chalk.bold.white
Start logging….
log(error('Error'));
log(info('Info'));
log(warn('Warn'));
log(debug('Debug'));
And - voila!
Isn’t that cool!!
It is easy to set it up.
The package makes use of String’s prototypical inheritance properties so you don’t have to worry about mutating its string properties when printing them in your terminal window.
At the time of writing, it garnered about 7000 stars (and still growing). The last time I checked is that the community code frequency is still active, so rest assured you’ll be able to count on them for providing ongoing support for this awesome toolkit to add your NodeJS collection goodies! There are more colours to choose from!
You can read it all here!
Till then, Happy Coding!