0
0
Expressframework~5 mins

Morgan for HTTP request logging in Express

Choose your learning style9 modes available
Introduction

Morgan helps you see details about each web request your server gets. It makes it easy to watch what happens in your app.

You want to know who is visiting your website and what pages they request.
You need to find out if your server is getting errors or slow responses.
You want to save logs of requests to check later for problems.
You are developing a web app and want to see live request info in the console.
You want to monitor traffic patterns to improve your app.
Syntax
Express
const morgan = require('morgan');
app.use(morgan('tiny'));

Use require('morgan') to import Morgan.

Use app.use(morgan('format')) to add logging middleware.

Examples
Logs detailed info including remote address, user agent, and response time.
Express
app.use(morgan('combined'));
Logs a short summary: method, URL, status, and response time.
Express
app.use(morgan('tiny'));
Custom format showing method, URL, status, response size, and time.
Express
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
Sample Program

This Express app uses Morgan with the 'tiny' format to log each request in the console.

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

const app = express();

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

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

You can choose different formats like 'combined', 'common', 'dev', 'short', and 'tiny'.

Logs appear in the console by default but can be saved to files with extra setup.

Morgan runs before your routes, so it logs every request your server gets.

Summary

Morgan logs HTTP requests to help you see what your server is doing.

Use app.use(morgan('format')) to add logging easily.

Pick a format that fits how much detail you want to see.