Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction  
2.
Debugging
3.
Logging
3.1.
Logging Express App Using Morgan
3.1.1.
Working
4.
Implementing Debugging and Logging in Express
4.1.
Prerequisites
4.2.
Step 1: Initialise npm 
4.3.
Step 2: Install all the required dependencies.
4.4.
Step 3: setting up express server
4.4.1.
Code 
4.4.2.
Explanation 
4.5.
Step 4: Run the server 
5.
Features of Debugging and Logging in Express
6.
Frequently Asked Questions
6.1.
What is debugging in Express?
6.2.
What is logging in Express?
6.3.
What is Morgan?
6.4.
What are the alternatives for Morgan in Express?
6.5.
How does Morgan work?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Debugging and Logging in Express

Introduction  

While building web applications, we face certain issues that hinder the flow of an application. But nothing is to be feared of, as Express provides us with debugging techniques through which we can track down these bugs and remove them from our application. Logging allows us to track the execution of our code, making it easy to understand the execution flow. 

Debugging and Logging in Express

In this article, we will understand debugging and logging in Express. We will discuss the process through which we can implement debugging and logging in express step by step with proper codes and output.

Debugging

Debugging refers to the process of fixing bugs and errors in software. The main aim is to find the root cause of the problem responsible for the application's unexpected behavior. It includes processes such as:

  • Analyzing code,
  • Examining system logs,
  • Running tests,
  • Using debugging tools
     

Express consists of a module called DEBUG that provides log information. The module tells about:

  • Middleware functions,
  • Application mode,
  • Status, 
  • Requests and responses made to the server.
     

You need to set up the DEBUG environment variable to use the DEBUG model. To set up the debugging environment in your express application, refer to the following link: Debugging Express. 

debugging and logging

There are several other alternatives other than the ‘debug’ module, such as using Node.js Debugger, Visual Studio Code Debugger, Node Inspector, ndb, Chrome Dev Tool, etc.

Logging

A logger is a software tool that helps record the events occurring in accessing any part of the web application. It is a crucial part of software development and helps a lot in debugging applications.

By combining debugging with logging, one can diagnose the issue in web applications effectively.

Logging Express App Using Morgan

Morgan is an Express middleware that provides the facility of request-logging. This means that whenever a client makes an HTTP request to the server, the request information can be recorded; this involves logging information about the HTTP method, status code, URL, etc.  To use Morgan in your express application, you need to run the following command in the terminal.

There are several other alternatives for logging HTTP requests, such as winston, pino, log4js, bunyan, debug-logger, winston-morgan, etc.

npm i morgan

 

Also, you must use the following statement in your app.js file: 

const morgan = require('morgan');
app.use(morgan('dev'));


Working


Morgan middleware interferes whenever we make a request to our express server before the requests the routes. It logs the necessary information such as URL, response, status code, etc. According to the specified log format. Morgan consists of many predefined log formats such as combined, common, dev, short, etc. It also provides us with the facility to create our own custom format.

logging in express

Moving forward, let's understand debugging and logging in express through an example for a better understanding.

Implementing Debugging and Logging in Express

Let's make an express application to demonstrate the working of debugging and logging in the express.

Prerequisites

You need to make sure you have the following installed in your system.

  • Node.js
     
  • A code editor (for example, VS code)

Step 1: Initialise npm 

As a first step, you need to initialize npm in the required directory by running the following command in the terminal.

cd FileName

 

npm init-y

 

We have used ‘-y’ flag to skip the process of filling the values and to accept the default values. You can also use ‘npm init’, if you wish to give custom values.

commands

Step 2: Install all the required dependencies.

Install all the dependencies for express, debugging, and logging by running the following command in the terminal.

npm i express debug morgan
command
output

Step 3: setting up express server

The ‘app.js’ file consists of the following code, with all the necessary debugging statements, and uses Morgan to track down the flow of execution.

Code
 

const express = require('express');
const debug = require('debug')('app:server');
const morgan = require('morgan');


const app = express();


// Morgan logging middleware - 'dev' format
app.use(morgan('dev'));


const NinjaData={

  Position:'SDE',
  age:25,
  
};


const SelectedNinja={

  name1:'Ninja1',
  name2:'Ninja2',
  
}


// Route handler for the homepage
app.get('/', (req, res) => {

  debug('Home page route triggered!'); 
  res.send('Hello Ninja!');

});


// Route handler for path-> /ninjadata
app.get('/ninjadata', (req, res) => {

   debug('ninjadata triggered');
   try {
   
     // A debug statement
    debug('Inside try block');

    const Selectedninja = SelectedNinja;
    const Ninjadata = NinjaData;
    res.json({ Selectedninja, Ninjadata});

  }

  catch (err) {

    debug('Error:', err.message);
    res.status(500).json({ error: 'Unexpected error' });

  }

});

// Start the server
app.listen(8000, () => {

console.log("server started on port 8000")

});


Explanation
 

In the above code, we have set up the node server to listen on the 8000 port, and the hostname is set to localhost. For implementing logging, we have used the statement: app.use(morgan('dev'));  Here, ‘dev’ is a pre-defined format provided by Morgan.

We have initialized two route handlers:

  • Path1: ‘/’ 
     
  • Path2: ‘/ninjadata’
     

In the path ‘/ninjadata’, we have used try’ and catch’ to handle exceptions.
 

  • Try: The code inside the try block is executed.
     
  • Catch:  If any error occurs while implementing the code in the try block, the program proceeds to the catch block to handle that exception.

Step 4: Run the server 

Run the above code by using the following command in the terminal:

For Windows :

set DEBUG=app:* & node app.js


For macOS (and other Unix-based systems):
 

DEBUG=app:* node app.js
command

Press enter, 

output

So, now your application is running on localhost:8000; you can see that in your browser. As you access ‘/’ path, you will see the debugging and logging statements in your terminal 

output

Debugging and logging statements in terminal:

output

Accessing the /ninjadata path:

output

Note: above, we have used the ‘JSON Viewer’ Chrome extension for a better format.

Debugging and logging statements in terminal:

output

In the above terminal output, the Debugging statements are:

app:server ninjadata triggered +27s
app:server Inside try block +0ms
 

The first line of the debugging statement tells us that the request for made to access the path ‘/ninjadata’, and the next line depicts that the flow of execution is now inside the ‘try’ block. Similarly, we can use other debug statements in our code.
 

In the above terminal output, the Logging Statement is: 

GET /ninjadata 200 4.292 ms - 93

This log format tells us about:

  • GET’ →HTTP method
  • ‘/ninjadata’ → URL path
  • 200 → HTTP status code (successful response)
  • ‘4.292’ → Response time
  • ‘93’ → Size of response (in bytes)
     

Therefore, we have successfully implemented debugging and logging in Express.

Features of Debugging and Logging in Express

Let's discuss some of the important features of debugging and logging in Express.
 

Debugging
 

  • Debugging helps in identifying errors and the root cause of unexpected behavior in an application by tracking down the flow of execution.
     
  • Through debugging, one can get real-time insights into the state of an application. This means the programmers can properly understand how the interaction is taking place between various parts of an application.
     
  • Debugging helps in focusing on specific problematic areas, thus reducing time and effort. This can be done by setting conditional breakpoints, which means that pausing the execution according to a certain condition.
     

Logging
 

  • Logging helps in recording important information in runtime. It helps the programmers in monitoring the execution and performance.
     
  • Logging also helps detect the problematic patterns that result in unexpected behavior of the system.
     
  • Logging enables us to customize the log formats. For example, in the above code, we used the ‘dev’ format; there are other formats, too, such as combines, common, dev, short, etc.

Refer to know about :  What is debugging

Frequently Asked Questions

What is debugging in Express?

Debugging refers to the process of fixing bugs and eros in software. The main aim is to find the root cause of the problem responsible for the application's unexpected behavior. 

What is logging in Express?

A logger is a software tool that helps record the events occurring in accessing any part of the web application. It is a crucial part of software development and helps a lot in debugging applications. By combining debugging with logging, one can help in diagnosing the issue in web applications.

What is Morgan?

Morgan is an Express middleware that provides the facility of request-logging. To use Morgan in your express application, you need to run the following command in the terminal, ‘npm i morgan’.

What are the alternatives for Morgan in Express?

There are several other alternatives for logging HTTP requests, such as winston, pino, log4js, bunyan, debug-logger, winston-morgan, etc.

How does Morgan work?

Morgan middleware interferes whenever we make a request to our express server before the requests the routes. It logs the necessary information such as URL, response, status code, etc.

Conclusion

In this article, we have learned about debugging and logging in Express. We have also seen the implementation of it using code and output. Refer to the following articles to further increase your knowledge in Express and accelerate your back-end development journey.
 

You can read more such descriptive articles on our platform, Coding Ninjas Studio. You will find straightforward explanations of almost every topic on the platform. So take your coding journey to the next level using Coding Ninjas.

 

Happy coding!

Live masterclass