Morgan: Request Logging
Objectives
By the end of this lesson, you should be able to:
- Install and configure Morgan to log every incoming request
- Choose between Morgan’s built-in log formats
- Explain why automatic request logging matters for a running server
💡 Why this matters: Lesson 1’s custom
loggermiddleware logged a method and URL by hand. Morgan is the standard, battle-tested package for exactly this job, with response times, status codes, and response sizes included automatically.
⚠️ A note on verification: every snippet and every response shown below was actually run and tested with real HTTP requests, using Morgan 1.11.
Installing and Using Morgan
npm install morgan
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Homepage');
});
app.get('/missing', (req, res) => {
res.status(404).send('Not found');
});
app.listen(4206);
Requesting / then /missing, server-side log output:
GET / 200 11.399 ms - 8
GET /missing 404 1.150 ms - 9
morgan('dev') is middleware (Lesson 1’s pattern again, morgan(...) returns a middleware function, app.use() registers it), logging every request’s method, path, status code, response time, and response size, with the status code color-coded in an actual terminal (green for success, yellow for client errors, not visible in plain text here). This single line replaces writing and maintaining a custom logging middleware by hand.
Morgan’s Built-in Formats
'dev' is the format used above, concise and colored, ideal for local development. 'combined' produces a more detailed, standard log format (including the client’s IP address and user agent), closer to what a production server’s access logs typically look like. 'tiny' is the most minimal format, just the essentials. Choosing a format is a single-argument change, morgan('combined') instead of morgan('dev'), no other code changes needed.
Try It
- Install Morgan, register it with the
'dev'format, and make several requests to different routes, confirming each one is logged with its method, path, and status code. - Switch to the
'combined'format, make the same requests, and compare the amount of detail logged. - Add a route that intentionally returns a
500status code, and confirm Morgan logs it distinctly (differently colored, in a real terminal) from a200. - Explain, in your own words, why relying on Morgan is preferable to maintaining the custom
loggermiddleware from Lesson 1 for a real project.
Recap
morgan(format)returns middleware that logs every request’s method, path, status, response time, and size automatically.'dev'is concise and colored for development,'combined'is closer to a production access log,'tiny'is minimal.- Morgan replaces hand-written logging middleware with a well-tested, configurable standard.
Next lesson: Helmet, setting security-related HTTP headers automatically.