Morgan is a popular HTTP request logger middleware for Node.js and Express.js. To implement request logging with the Morgan library in an Express.js application, follow these steps:
Install Morgan: Make sure you have Morgan installed in your project. You can install it using npm:
bashnpm install morgan
Import Morgan and Set Up Logging:
In your Express.js application, import Morgan and set it up to log requests. You typically do this near the top of your app.js
or server.js
file.
javascriptconst express = require('express');
const morgan = require('morgan');
const app = express();
// Use Morgan for logging requests
app.use(morgan('combined')); // 'combined' is a pre-defined log format, but you can customize it
// ...rest of your Express.js application setup
In the example above, app.use(morgan('combined'))
tells Morgan to log requests using the 'combined' format, which includes detailed information about each request.
Customize Logging Format (Optional):
You can customize the log format by providing your own format string to the morgan
function. For example:
javascriptapp.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
Here, :method
, :url
, :status
, :res[content-length]
, and :response-time
are placeholders for different information about the request and response. You can find a list of available tokens in the Morgan documentation.
Handle Logging in Different Environments (Optional):
You might want to enable or disable logging based on your application's environment (development, production, etc.). You can do this by checking the NODE_ENV
environment variable.
javascriptconst isDevelopment = process.env.NODE_ENV === 'development';
if (isDevelopment) {
app.use(morgan('dev')); // Use a more detailed log format in development
} else {
app.use(morgan('combined')); // Use the 'combined' format in production
}
This way, you can have more detailed logs during development and cleaner logs in production.
Start your Express.js Server: Finally, make sure to start your Express.js server as usual:
javascriptconst PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
With these steps, you've successfully integrated the Morgan library into your Express.js application for request logging. Adjust the logging format according to your preferences and requirements.