How we built a Node.js Middleware to Log HTTP API Requests and Responses
Building a middleware to log HTTP API requests and responses in Node.js can be very useful for debugging and monitoring purposes. Here is an example of how to build such a middleware:
// app.js
const express = require(‘express’);
const logger = require(‘./middleware/logger’);
const app = express();
// Add the logger middleware to the application
app.use(logger);
// Define your API routes here
app.get(‘/’, (req, res) => {
res.send(‘Hello World!’);
});
app.listen(3000, () => {
console.log(‘Server started on port 3000’);
});
// middleware/logger.js
const logger = (req, res, next) => {
const { method, url } = req;
const start = new Date();
res.on(‘finish’, () => {
const end = new Date();
const duration = end – start;
console.log(`${method} ${url} ${res.statusCode} ${duration}ms`);
});
next();
};
module.exports = logger;
In this example, we first define an express
application in app.js
. We then import our logger
middleware from the middleware/logger.js
file and add it to the application using the app.use()
method.
Our logger
middleware function takes three arguments: req
, res
, and next
. It first extracts the HTTP method and URL from the request object, and creates a new Date
object to record the start time of the request.
We then listen for the finish
event on the response object, which is emitted when the response has been fully sent to the client. In the event listener, we calculate the duration of the request by subtracting the start time from the end time, and log the HTTP method, URL, response status code, and duration in milliseconds to the console.
Finally, we call the next()
function to pass control to the next middleware or route handler in the stack.
With this middleware in place, every HTTP request and response made to our API will be logged to the console with the relevant information. This can be very useful for debugging and monitoring purposes, especially in production environments.
Upcoming Request Movies
Leave a Message