Back to Blog

On demand & colorful console log in NodeJS

October 02, 2019
#node
  
#nodejs
  
#console
  
#ondemand
  
#logging
  

We all know and use console.log while working in JavaScript. Be it any framework (like react) or NodeJS. In case of NodeJS, we can see the console log output in our terminal. At some point of time we try to remove some or add some of the console.log during development or while trying to deploy it. What if we can toggle the logging when needed? And, what if we can add some color also to distinguish between different log messages.

To start with, let’s create one simple server.js file. It will look something like below:

// Dependencies
const http = require('http');

//create a server:
const server = http.createServer((req, res) => {
  console.log('Write response')
  res.write('Hello NodeJS!') //write a response to the client
  res.end() //end the response
  console.log('Response ended.')
});

// start listening to the server
server.listen(8080, () => {
  console.log('Node server is listening on 8080 port.')
});

I have added some extra console messages for explanation.

Now, when we start the server using node server.js, the terminal is going to output log message as shown below:

nodejs-log-1

Alright!

Now, let’s modify the server.js file to enable on-demand logging.

First, modify the server.js. Updated code is given below:

// Dependencies
const http = require('http');
const util = require('util');
const debugLog = util.debuglog('server');

//create a server:
const server = http.createServer((req, res) => {
  debugLog('Write response');
  res.write('Hello NodeJS!'); //write a response to the client
  res.end(); //end the response
  debugLog('Response ended.');
});

// start listening to the server
server.listen(8080, () => {
  debugLog('Node server is listening on 8080 port.');
});

We can see couple of changes here. Let me try to explain it stepwise.

  • First of all, I have added one require statement at Line 3 to import util
  • In next line (Line 4), I have created a reference to debuglog method call done using util. Important thing to note here is the parameter provided in function call: server.
  • Finally, we replace our console.log statement with debugLog variable created at Line 4

Once changes are done, if we run the server using node server.js command, no console output will be shown.

So, you must be thinking that how to show the logs then?

Well, to see the log, we need to change our command a little. New command syntax would be NODE_DEBUG=server node server.js. Refer the screenshot below:

nodejs-log-2

We can observe couple of changes in the above image. Let’s try to understand those.

  1. NODE_DEBUG=server -> When we set NODE_DEBUG to server, it logs only those messages that is related to the key we passed during the initialization of util.debuglog('server'). This way, we can have different on-demand logging across file.
  2. While the output is coming, it also adds a keyword before. In the above case it added SERVER 10072:. This helps us to understand that which part of application this log belongs to or the keyword we have given to. A nice and clean way to differentiate our log too. :)

Coming to the second part where I have mentioned to have colourful console. Usually, we use console.log like this:

console.log('Hello console');

Going forward, try to use it in this way:

console.log('\x1b[36m%s\x1b[0m', 'Hello console');

And the output will be like this:

nodejs-log-3

Isn’t that cool?

I know, a bit of explanation is needed. So, the first parameter in console.log is instructing the terminal to change the text color. And %s is the placeholder for our log message. Now, to change the color to different value, simply play around with the number after [ and before m. In the above example, we can update 36 to 31 to get red variant.

This works with the on-demand logging also (explained above). And we can get something like below:

nodejs-log-4

Looks gorgeous, right.

In similar fashion, we can change the background of the log message instead of text color. I am providing the values for reference here. Go ahead and try these.

Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"

In the example given above, replace the content from start till m letter with any one of the above and check the output. Feel free to add comments below with some nice looking console messages here and with the code used.

Thank you for reading.

Happy learning!

Anand Kumar
Manager at PublicisSapient
Back to Blog