Blog>
Snippets

Server-side Request Logger

Create middleware that logs incoming requests to the server including method, URL, and response time.
const express = require('express');
const app = express();

// Middleware to log requests
app.use((req, res, next) => {
    const startHrTime = process.hrtime();

    res.on('finish', () => {
        const elapsedHrTime = process.hrtime(startHrTime);
        const elapsedTimeInMs = (elapsedHrTime[0] * 1000 + elapsedHrTime[1] / 1e6).toFixed(3);
        console.log(`${req.method} ${req.path} - ${res.statusCode} ${elapsedTimeInMs}ms`);
    });

    next();
});

// Other middleware and route handlers go here...

app.listen(3000, () => console.log('Server is running on port 3000'));
This code snippet creates an Express.js server and middleware that logs the method, path, status code and response time of each incoming request. The middleware uses `process.hrtime()` to get high-resolution real time to measure how long a request takes to process. When the response has finished being sent (`res.on('finish')`), it logs this information to the console before passing control to the next middleware function.