morgan middleware in express
To use morgan
middleware in an Express.js application, you typically install it via npm and then require it in your main application file (e.g., app.js
or index.js
). Here's a basic example of how you can set up morgan
:
-
Install
morgan
: First, installmorgan
using npm or yarn if you haven't already:npm install morgan
-
Require and Use
morgan
in Your Express App:In your main application file (
app.js
orindex.js
), requiremorgan
and use it as middleware:const express = require('express'); const morgan = require('morgan'); const app = express(); // Use morgan middleware with 'dev' format app.use(morgan('dev')); // Define your routes and other middleware // Example route app.get('/', (req, res) => { res.send('Hello World!'); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
-
Explanation:
const morgan = require('morgan');
: Importmorgan
into your application.app.use(morgan('dev'));
: Usemorgan
middleware with the 'dev' format.'dev'
is one of the pre-defined formats inmorgan
that gives you concise output colored by response status for development use.- You can replace
'dev'
with other formats like'combined'
,'common'
, or create custom formats as per your logging needs. For example:
This format provides more detailed logging information.app.use(morgan('combined'));
-
Start Your Server: Finally, start your Express server using
app.listen()
as shown in the example.
When you run your Express application after setting up morgan
middleware, you'll see HTTP request details (like method, URL, status code, response time, etc.) logged to the console, which is helpful for debugging and monitoring your application's requests.