How to Create a Custom Logger in Express for Better Request Tracking
To create a custom logger in
Express, write a middleware function that logs request details like method and URL, then call next() to continue. Use app.use() to apply this middleware globally so every request is logged.Syntax
A custom logger in Express is a middleware function with three parameters: req (request), res (response), and next (to pass control). Inside, you log details and call next() to let Express continue processing.
req.method: HTTP method (GET, POST, etc.)req.url: Requested URLnext(): Moves to next middleware or route handler
javascript
function customLogger(req, res, next) { console.log(`${req.method} ${req.url}`); next(); } app.use(customLogger);
Example
This example shows a complete Express app with a custom logger middleware that prints the HTTP method and URL for each request. It then responds with a simple message.
javascript
import express from 'express'; const app = express(); // Custom logger middleware function customLogger(req, res, next) { console.log(`Request: ${req.method} ${req.url}`); next(); } // Use the logger for all routes app.use(customLogger); // Simple route app.get('/', (req, res) => { res.send('Hello from Express with custom logger!'); }); // Start server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Request: GET /
Common Pitfalls
Common mistakes when creating a custom logger in Express include:
- Not calling
next()inside the middleware, which stops the request from continuing. - Logging too much or sensitive data, which can clutter logs or expose private info.
- Placing the logger after route handlers, so it never runs.
Always place the logger middleware before routes and keep logs clear and relevant.
javascript
/* Wrong: missing next() stops request */ function badLogger(req, res, next) { console.log(`${req.method} ${req.url}`); // next() missing here } /* Right: call next() to continue */ function goodLogger(req, res, next) { console.log(`${req.method} ${req.url}`); next(); }
Quick Reference
- Middleware signature:
(req, res, next) => void - Log request method and URL with
req.methodandreq.url - Always call
next()to continue processing - Use
app.use(yourLogger)to apply globally - Place logger before routes for full coverage
Key Takeaways
Create a middleware function with parameters (req, res, next) to log requests.
Always call next() inside your logger to avoid blocking requests.
Use app.use() to apply your logger middleware before defining routes.
Keep logs simple and avoid logging sensitive information.
Test your logger by making requests and checking console output.