Node.js › Express & Middleware
How would you implement a request-logging middleware in Express that captures method, path, status code, and response time for every request?
AdvancedAnswer
A logging middleware records the request's start time when it first runs, then attaches a listener to the response's 'finish' event (fired once the response has been fully sent) to calculate the elapsed duration and log the complete request/response summary -- this pattern, rather than logging synchronously right after calling next(), is necessary because next() returns before the response is actually sent, so the status code and true total duration aren't known until the response actually finishes.
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.path} ${res.statusCode} ${duration}ms`);
});
next();
});Real-world example An API's custom logging middleware records every request's method, path, final status code, and total response time by listening for the response's 'finish' event, giving operations visibility into which endpoints are slow or frequently erroring without needing a third-party logging library.