What is Morgan middleware?
Morgan is a popular HTTP request logger middleware for Node.js, primarily used with web frameworks like Express.js. It helps developers log details about incoming HTTP requests to their server, which is crucial for debugging, monitoring, and understanding application traffic.
What is Morgan?
Morgan functions as middleware in your Node.js application's request-response cycle. Its primary role is to intercept HTTP requests and log information such as the request method, URL, status code, response time, and more. This logging capability is invaluable for debugging during development, monitoring live applications, and gathering analytics.
It supports various pre-defined log formats, making it easy to get started, and also allows for highly customizable log formats to suit specific needs.
Key Features and Benefits
- Pre-defined Log Formats: Offers several built-in formats (e.g., 'dev', 'tiny', 'short', 'common', 'combined') to quickly configure logging output.
- Customizable Formats: Allows you to define your own log tokens and create entirely custom logging formats.
- Stream Support: Can pipe log output to any writeable stream, enabling logging to files, external services, or the console.
- Conditional Logging: Supports defining a
skipfunction to conditionally log requests based on certain criteria (e.g., skipping static file requests). - Easy Integration: Seamlessly integrates with Express.js and other Connect-compatible Node.js frameworks.
How to Use Morgan
Installation
Morgan can be installed via npm:
npm install morgan
Basic Usage with Express
To use Morgan, you typically require it in your main application file and then use it as middleware with app.use().
const express = require('express');
const morgan = require('morgan');
const app = express();
// Use the 'dev' format for logging in development mode
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Custom Formats
You can define custom tokens and formats using the morgan.token() and morgan() functions.
const express = require('express');
const morgan = require('morgan');
const app = express();
// Define a custom token for the request body (example, needs body-parser for real use)
morgan.token('body', function (req, res) { return JSON.stringify(req.body) });
// Use a custom format string
app.use(morgan(':method :url :status :response-time ms - :res[content-length] :body'));
app.get('/', (req, res) => {
res.send('Hello from custom logger!');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Logging to a File
Instead of the console, you can direct Morgan's output to a file using Node.js's fs.createWriteStream.
const express = require('express');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const app = express();
// Create a write stream (in append mode)
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });
// Setup the logger to use 'combined' format and output to the stream
app.use(morgan('combined', { stream: accessLogStream }));
app.get('/', (req, res) => {
res.send('Logs written to access.log');
});
app.listen(3000, () => {
console.log('Server running on port 3000, logs writing to access.log');
});
Common Log Formats
| Format Name | Description |
|---|---|
| `combined` | Apache combined log format. Includes `remote-addr`, `remote-user`, `date`, `method`, `url`, `http-version`, `status`, `res[content-length]`, `referrer`, `user-agent`. |
| `common` | Apache common log format. Includes `remote-addr`, `remote-user`, `date`, `method`, `url`, `http-version`, `status`, `res[content-length]`. |
| `dev` | A concise output colored by response status for development. Includes `method`, `url`, `status`, `response-time ms`. |
| `short` | Shorter than `dev`, includes `remote-addr`, `remote-user`, `method`, `url`, `http-version`, `status`, `res[content-length]`, `response-time ms`. |
| `tiny` | The minimal output. Includes `method`, `url`, `status`, `res[content-length]`, `response-time ms`. |
Why Use Morgan?
Using Morgan brings several advantages to Node.js development and production environments:
- Debugging: Quickly identify problematic requests, errors, or unexpected behavior during development.
- Monitoring: Gain insights into the types of requests your application is handling, traffic patterns, and potential performance bottlenecks in production.
- Auditing: Keep a record of all requests for security audits or compliance requirements.
- Performance Analysis: Observe response times to pinpoint slow endpoints and optimize them.
- Customization: Tailor logs precisely to your needs, including specific headers, user information, or body data (with additional parsing middleware).