Power of Eloquence

When saying “Hello World!” isn’t enough anymore

NodeJS Logging With Chalk

| Comments

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.

Load up the chalk module
1
const chalk = require(chalk);

Store console.log as a separate module.

Get ready to log using Chalk
1
2
const chalk = require('chalk');
const log = console.log;

Next, you define your logging colour classification for your needs.

Setup different logging preformatted color variables
1
2
3
4
const error = chalk.bold.red
const info = chalk.bold.blue
const warn = chalk.bold.yellow
const debug = chalk.bold.white

Start logging….

Now they’re going to look pretty
1
2
3
4
log(error('Error'));
log(info('Info'));
log(warn('Warn'));
log(debug('Debug'));

And - voila!

Chalk logging

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!

Comments