0
0
Expressframework~3 mins

Why Morgan for HTTP request logging in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could see every visitor's action on your server without writing extra code for each page?

The Scenario

Imagine you run a small web server and want to know who visits your site and what pages they look at.

You try to write code that prints every request manually inside each route handler.

It quickly becomes messy and hard to keep track of all requests.

The Problem

Manually adding logging code everywhere is slow and easy to forget.

You might miss logging some requests or log inconsistent details.

This makes it hard to debug problems or understand user behavior.

The Solution

Morgan is a tool that automatically logs every HTTP request for you.

You add it once to your server setup, and it handles all the logging consistently and clearly.

This saves time and gives you reliable logs to understand your app's traffic.

Before vs After
Before
app.get('/', (req, res) => {
  console.log(`${req.method} ${req.url}`);
  res.send('Hello');
});
After
const morgan = require('morgan');
app.use(morgan('tiny'));
What It Enables

With Morgan, you can easily monitor and debug your web server traffic without extra effort.

Real Life Example

A developer notices their website is slow and uses Morgan logs to find which requests take too long.

This helps them fix the problem quickly.

Key Takeaways

Manual logging is error-prone and hard to maintain.

Morgan automates HTTP request logging with one setup step.

It provides clear, consistent logs to help monitor and debug your server.