Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7759

How to to create a custom logger in Express?

During an exercise in school we have been tasked with making custom middleware in Express:

This might be tricky. Make it so that your custom logging middleware also logs out the eventual response status code. For example, after a successful GET request to / you should see:

GET / 200

I tried this:

app.use(function(req, res, next) {
  console.log(chalk.green(req.method, req.url, res.statusCode));
  next();
});

It appears to work but then I noticed upon trying a uri which doesn't exist I still get:

GET /foo 200

Does this mean the request i.e. GET, is working but has nothing to do if the resource is there?

Also how would I implement error handling, in this instance I tried:

app.use(function(err, req, res, next) {
  if (err) {
    console.log(err);
  } else {
    console.log(chalk.green(req.method, req.url, res.statusCode));
  }
  next();
});

But that didn't work at all! Thanks in advance!

Upvotes: 1

Views: 3426

Answers (1)

idbehold
idbehold

Reputation: 17168

app.use(function(req, res, next) {
  if (res.headersSent) {
    console.log(chalk.green(req.method, req.url, res.statusCode));
  } else {
    res.on('finish', function() {
      console.log(chalk.green(req.method, req.url, res.statusCode));
    })
  }
  next();
});

Upvotes: 3

Related Questions