Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptIntroduction to Morgan.js

Introduction to Morgan.js

Morgan is a middleware that logs HTTP requests and errors. Middleware is simply a function that has access to the request and response lifecycle methods. We can either use predefined formats or create new ones to format our logs.

Installation of morgan:

Step 1: You can visit morgan for the documentation. The package can be installed with this command.

npm install morgan

Step 2: After the installation is completed you can check the installed version of the package with this command:

npm ls morgan

Step 3: To start working with morgan create a file with the name index.js. The package can be included in the index.js with this command.

const morgan = require('morgan')

Step 4: To use morgan we have to invoke an instance and pass it as an argument to the app.use() which is an express middleware before HTTP requests. This can be done as follows:

app.use(morgan(string));

The string above defines the format in which we want to log our information.

Project Structure: The project structure will look like the below image.

Morgan has five predefined formats that we can use directly to get the required information. These are:

  1. combined:  It gives the Apache standard combined format logs.
  2. common: It gives Standard Apache common log output.
  3. dev: It is a color-coded log format.
  4. short: It is shorter than the default format. It also includes the response time.
  5. tiny: It is the shortest log that contains very little information.

The output format of all these predefined formats can be found here.

Example 1:

index.js




// Requiring modules
const express = require("express");
const morgan = require("morgan");
const app = express();
  
// Using combined predefined format
app.use(morgan("combined"));
  
// Creating an endpoint where 
// requests can be made and
// we can get logs
app.get("/", (req, res) => {
  res.send("neveropen");
});
  
// Running on PORT
const PORT = 5000;
  
app.listen(PORT, () => {
  console.log(`Running on PORT: ${PORT}`);
});


Step to run the application: In the terminal run the following command to execute the index.js file.

node index.js

Output:

::1 - - [10/Feb/2021:22:18:30 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0
(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/88.0.4324.150 Safari/537.36"

When you will visit https://localhost:5000 the above log will appear in the console. The log gives us various information like the date and time when the request was made, method of request which is GET in this case, to which URL the request was made which is ‘/’, and much more.

Example 2:

index.js




// Requiring modules
const express = require("express");
const morgan = require("morgan");
const app = express();
  
// Using dev predefined format
// Returns
app.use(morgan("dev"));
  
// Creating an endpoint where
// requests can be made and
// we can get logs
app.get("/home", (req, res) => {
  res.send("neveropen");
});
  
// Running on PORT
const PORT = 5000;
  
app.listen(PORT, () => {
  console.log(`Running on PORT: ${PORT}`);
});


Output:

When you visit “https://localhost:5000”, the output will be:

GET / 404 4.031 ms - 139

Since we do not have any endpoint for the “/” URL we end up getting a 404 error with the method of type GET and response time in milliseconds.

When you visit  “https://localhost:5000/home”, the output will be:

GET /home 200 3.416 ms - 13

In our program, we have created an endpoint of “/home” so we get a response of 200 in return.

Example 3:

index.js




// Requiring modules
const express = require("express");
const morgan = require("morgan");
const app = express();
  
// Creating customised logs
// :method return method used like - GET,POST
// :url returns to which url request was made
// :status returns the status returned from req like - 200,404
// :response-time returns the time it took to give response
// Rest things are printed as it is
app.use(
  morgan(
    "Method- :method URL- :url Status- :status ResponseTime-  :response-time ms"
  )
);
  
// Creating an endpoint where
// requests can be made and
// we can get logs
app.get("/home", (req, res) => {
  res.send("neveropen");
});
  
// Running on PORT
const PORT = 5000;
  
app.listen(PORT, () => {
  console.log(`Running on PORT: ${PORT}`);
});


Output:

Method- GET URL- /home Status- 200 ResponseTime-  3.392 ms

In the above program, we have customized our output log. The format is : followed by the information name. These are predefined tokens that can be added by using in front of them.

We can also create custom tokens with the help of the .token() method. See the below example:

Example 4:

index.js




// Requiring modules
const express = require("express");
const morgan = require("morgan");
const app = express();
  
// Creating custom token
// with name time
morgan.token(
  "time",
  " :method request for :url was received.Response time: :response-time"
);
  
// Using the name of
// token we created above
app.use(morgan("time"));
  
// Creating an endpoint where
// requests can be made and
// we can get logs
app.get("/home", (req, res) => {
  res.send("neveropen");
});
  
// Running on PORT
const PORT = 5000;
  
app.listen(PORT, () => {
  console.log(`Running on PORT: ${PORT}`);
});


Output:

GET request for /home was received.Response time: 5.567

Morgan is a very simple logger that allows flexibility when logging HTTP requests and gives us the required information. So this is how we can use morgan in our application

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments