Logging request with “Morgan” in Node JS.

To log requests using Morgan in Node.js, you first need to install the Morgan package:

npm install morgan

Then, you can integrate Morgan into your Node.js application. Here’s an example of how you can use Morgan with Express.js:

const morgan = require('morgan');

and use it below where Cors are used.

// Use Morgan middleware to log requests

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

We import both Express.js and Morgan.

We create an Express app instance.

We use Morgan middleware by calling app.use(morgan('dev')). The 'dev' format is one of the predefined formats provided by Morgan, which provides concise output for development. There are other formats available as well, such as 'combined' or 'common'.

We define our routes as usual.

We start the server, listening on the specified port.

Leave a comment

Your email address will not be published. Required fields are marked *