
How to log Node JS http requests using morgan
Morgan is a third-party middleware or module used to log every http request information in details as customized by the developer. This is a very useful dev tool.
Morgan makes work lot more easier and flexible.
Before using Morgan, make sure Morgan has been installed or install via npm with the command:-

npm install --save morgan
Or as a dev dependency,
npm install --save-D morgan
We will implement the simplest use case of morgan to easily get started with morgan.
Syntax
morgan (format, options)
- Format refers to the “way” in which the request info should be logged on the console. Morgan comes with predefined formats which helps developers to easily setup and use morgan.
- The options argument is an object used to further customize the functioning of morgan.
Note that, each format has something special in the way it logs request.
We will use the “tiny” predefined format in our code below and view the output on our cmd console.
The output for the “tiny” predefined format is: -method -url -status code -response content length -response time.
const express = require ('express');
const morgan = require ('morgan');
const app = express ();
app.use(morgan('tiny')) // or dev or combined or common or any predefined format
app.get('/',(req, res)=>{
res.send('Home page')
})
app.get('/about',(req, res)=>{
res.send('about page')
})
app.listen(3000,()=>{
console.log('code running on port 3000');
})
Output

Morgan at work after 2 successful http GET requests (home and about routes).
Thanks for coding with me..
Hope you learnt something new. You can always drop your comments and share with other devs. Remember we will cover more real code and projects in the next tutorials.
Links: Morgan Web Page, NPM Website
Leave a Comment