What if you could see every visitor's action on your server without writing extra code for each page?
Why Morgan for HTTP request logging in Express? - Purpose & Use Cases
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.
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.
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.
app.get('/', (req, res) => { console.log(`${req.method} ${req.url}`); res.send('Hello'); });
const morgan = require('morgan'); app.use(morgan('tiny'));
With Morgan, you can easily monitor and debug your web server traffic without extra effort.
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.
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.
Practice
morgan in an Express app?Solution
Step 1: Understand Morgan's role
Morgan is a middleware that logs details about HTTP requests to the console or a file.Step 2: Compare options with Morgan's function
Only logging HTTP requests matches Morgan's purpose; other options relate to different tasks.Final Answer:
To log HTTP requests for monitoring server activity -> Option AQuick Check:
Logging HTTP requests = A [OK]
- Confusing Morgan with session or static file middleware
- Thinking Morgan manages database connections
- Assuming Morgan serves files
Solution
Step 1: Recall Morgan usage syntax
Morgan is used as middleware by callingmorgan('format')insideapp.use().Step 2: Check each option's syntax
Onlyapp.use(morgan('tiny'))matches the correct syntax; others are invalid method calls or parameters.Final Answer:
app.use(morgan('tiny')) -> Option BQuick Check:
Use morgan('format') inside app.use() = D [OK]
- Calling morgan as a method like morgan.tiny()
- Passing strings directly to app.use() without morgan()
- Using non-existent morgan.format() method
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get('/', (req, res) => res.send('Hello'));
app.listen(3000);Solution
Step 1: Identify the HTTP method and route
The code handles GET requests to '/', so a GET / request is valid and returns 200 status.Step 2: Understand Morgan 'dev' format output
The 'dev' format logs method, URL, status code, response time, and response size roughly like 'GET / 200 5 - 0.123 ms'.Final Answer:
GET / 200 5 - 0.123 ms -> Option AQuick Check:
GET / with 200 status logs as in B [OK]
- Confusing POST with GET method
- Assuming 404 status for existing route
- Expecting error from Morgan format
app.use(morgan('combined')), but no logs appear in the console. What is the most likely cause?Solution
Step 1: Understand middleware order importance
Express runs middleware in order. If Morgan is added after routes, requests may not pass through it.Step 2: Check Morgan format and behavior
'combined' is a valid format; Morgan logs all requests, not just errors; it does not need a database.Final Answer:
Morgan middleware is added after route handlers -> Option CQuick Check:
Middleware order matters; Morgan must be before routes [OK]
- Thinking 'combined' format is invalid
- Believing Morgan logs only errors
- Assuming Morgan needs a database
Solution
Step 1: Understand Morgan's skip option
The 'skip' option is a function that returns true to skip logging that request.Step 2: Apply condition to skip requests with status below 400
To log only 400 or higher, skip requests where statusCode is less than 400.Step 3: Verify other options
'filter' and 'only' are not valid Morgan options; app.use(morgan('combined', { skip: (req, res) => res.statusCode >= 400 })) skips 400+ which is opposite of desired.Final Answer:
app.use(morgan('combined', { skip: (req, res) => res.statusCode < 400 })) -> Option DQuick Check:
Skip if status < 400 to log 400+ [OK]
- Using skip condition backwards
- Using invalid options like filter or only
- Confusing skip with logging condition
Ready to prove it?
Pass the test and this pattern moves unknown
