Published on

Logging requests in Express app with middleware

Authors

This post introduces a solution for endpoints logging in Express app. While Winston library is being used in this particular case, the solution could be used with any other logger.

Example

This solution type is called middleware. Middleware serves multiple functions, including but not limited to message passing, authentication, API management, data transformation, and session management. Its primary goal is to simplify the development process by abstracting underlying architectural complexities, allowing developers to focus on the specific business logic of their applications.

In this example, let's start by adding Winston as a dependency to your existing ExpressJS project:

npm install winston

Next, let's write the middleware function. It should include request, response and next action as a parameter. Calling next() after logging method is required in order for process to proceed after middleware's action has been executed. request-logging.js example:

import logger from '../utils/logger.js';

const requestLogging = (req, res, next) => {
    logger.info('Request:', {
        method: req.method,
        path: req.path,
        body: req.body,
        query: req.query,
    });
    next();
};

export default requestLogging;

Finally, let's add the middleware to app's setup:

import requestLogging from './middlewares/request-logging.js';
app.use(requestLogging);

And here is the folders structure for this example:

src/
|
|-- config/
|
|-- middlewares/
|   |
|   |-- authenticate.js
|   |-- firebase-request.js
|   |-- not-found.js
|   |-- request-logging.js
|   |-- request-performance-logging...
|
|-- network/
|
|-- utils/
|   |
|   |-- logger.js
|
|-- app.js

After starting the project and triggering the endpoint, we can see log looking somehow like this:

info: Request: {"body":{},"method":"GET","path":"/","query":{},"service":"user-service"}

Conclusion

We've covered a simple yet effective setup of logging with Winston using middleware solution. I hope you enjoyed the post. Feel free to follow me on social media platform of your choice and ask your questions related to this post! Thank you for reading.