1.

How to use the debug logger in an express app?

Answer»

The DEBUG logger is more like our console logs, but it shows the log in a beautiful and colorful way. Additionally, you can turn certain modules on and off for logging. Let’s take a look at an example. 

We need to first create a new folder and change directory. After that we need to create a Node.js application by giving the command npm init -y. Next, we will install express, debug and http modules in it by giving the command npm i express debug http from the command line. 

Now, we are creating a BASIC app with the http module and enabling logging in it. The line const log = debug(‘http:server’), means that our server is called by that name. 

Now, when we go to the terminal and give the command DEBUG=http:server node index.js , we will see the below output from Line 6 and Line 12.  

Now, go to http://localhost:3000/ and we will see the log output from Line 9 from index.js in our console. 

As mentioned earlier, one of the main features of the debug logger is to do selective logging. To SHOW that we will create a fake ERROR in our app, which is using setTimeout() and running after 1 second. Also, NOTICE that we have a new errorLogger with the name http:error declared.  

Now, to see only this log, we have to change our command in the terminal to DEBUG=http:error node index.js , we will see the below output fromLine 13, after 1 second. 

Now, if we turn on all the logs with *, we will see all the logs in the terminal.  



Discussion

No Comment Found