DEV Community

farakh-shahid
farakh-shahid

Posted on

What is a Logger Middleware

What is a Logger Middleware?

A logger middleware in Node.js is a piece of code that intercepts incoming HTTP requests and logs information about them. It helps in monitoring and debugging server-side applications by providing insights into request details such as the HTTP method, URL, timestamp, and other relevant information.

Setting up the Project

Before we dive into the code, make sure you have Node.js installed on your system. Create a new directory for your project, open a terminal, and navigate to the project directory. Run the following command to initialize a new Node.js project:

$ npm init -y
Enter fullscreen mode Exit fullscreen mode

This will create a new package.json file, which will be used to manage project dependencies.

Installing Dependencies

We'll be using the Express.js framework to create our server and the morgan library for logging. Install these dependencies by running the following command:

$ npm install express morgan

Enter fullscreen mode Exit fullscreen mode

Once the installation is complete, you can proceed to the code implementation.

Implementing the Logger Middleware

Create a new file called app.js and open it in your preferred code editor. Let's begin by requiring the necessary modules and setting up the basic Express server:

const express = require('express');
const morgan = require('morgan');

const app = express();
const port = 3000;

app.use(morgan('dev'));

// ... Additional code will be added here

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Enter fullscreen mode Exit fullscreen mode

Here, we import the required modules and create an instance of the Express application. We also specify the port on which the server will run. The morgan('dev') statement sets up the logger middleware using the 'dev' predefined format, which provides concise logging output.

Testing the Logger Middleware

To test the logger middleware, let's create a simple route that will respond with a sample JSON message. Add the following code below the existing code:

app.get('/', (req, res) => {
  res.json({ message: 'Hello, world!' });
});

Enter fullscreen mode Exit fullscreen mode

Logging Output

With the server running, open your browser and navigate to http://localhost:3000. You should see the JSON response message. Meanwhile, in your terminal, you'll notice logs generated by the logger middleware in the 'dev' format:

GET / 200 6.802 ms - 20

Enter fullscreen mode Exit fullscreen mode

References:

1.https://expressjs.com/en/resources/middleware/morgan.html
2.https://www.linkedin.com/pulse/log-http-requests-express-middleware-nodejs-ahmad-alinaghian/

Top comments (0)