Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed luctus dignissim quam id fringilla. Aliquam erat volutpat. Integer sodales pretium efficitur. Nullam quis sollicitudin urna. Etiam vel massa a erat mollis lacinia.
Installation
- Open your terminal.
- Navigate to your project’s root directory.
- Run the following command to install Morgan:
npm install morgan
Basic Usage
To start using Morgan, require it in your project:
const morgan = require('morgan');
Then, add the Morgan middleware to your Express app:
app.use(morgan('common'));
Configuration
You can customize Morgan’s logging format by passing different options during initialization:
app.use(morgan('common', {
skip: (req, res) => res.statusCode < 400
}));
Logging Formats
Morgan supports various logging formats:
morgan('combined')
Available Formats
Below are the available predefined formats:
combined
common
dev
short
tiny
Custom Formats
You can create your own logging format by specifying a function:
morgan((tokens, req, res) => {
return [
tokens.method(req, res),
tokens.url(req, res),
// additional tokens...
].join(' ');
});
Middleware Options
Here are the available options when using Morgan as middleware:
Option | Description |
---|---|
immediate |
Log requests before they are handled by your routes. |
skip |
Skip logging based on custom condition. |
stream |
Write logs to a custom output stream. |
Conclusion
Now you have a basic understanding of how to use Morgan for logging HTTP requests in your Express app. Explore different formats, customize your own, and make use of the available middleware options to enhance your logging experience.