How can i create a logger middleware in express without any package or library

6.3k Views Asked by At

I've trying to create a custom logger middleware without any package or library It's as simple as saving the endpoint, the method and the status code response.

I have the problem when I try to save the status code, since my response has not yet reached the controller. I was trying to understand how morgan does it, because it is the first middleware I use and when my backend responds, it logs the status code.

Is there a simple way without me having to modify all my backend controllers?

Or rather, how can I access the res.status of a controller from this middleware?

const createLog = (req, res, next) => {
  const { method, url } = req;
  const { statusCode, statusMessage } = res;

  console.log(statusCode, statusMessage); // Both null when reach the middleware
  next();
};
1

There are 1 best solutions below

0
On BEST ANSWER

Try this here:

const createLog = (req, res, next) => {
  res.on("finish", function() {
    console.log(req.method, decodeURI(req.url), res.statusCode, res.statusMessage);
  });
  next();
};