UpTheCreek
UpTheCreek

Reputation: 32381

Express.js - logging only failed requests

Is there a way to get the express.js logger to log only failed requests?

E.g. 4xx and 5xx, but not logging 3xx results?

Upvotes: 0

Views: 302

Answers (1)

robertklep
robertklep

Reputation: 203231

I haven't found an easy way to do that, but I came up with this:

function compile(fmt) {
  fmt = fmt.replace(/"/g, '\\"');
  var js = '  return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){
    return '"\n    + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "';
  }) + '";'
  return new Function('tokens, req, res', js);
};

var formatter = compile(express.logger.default); // or another format, like '.tiny', '.dev'

app.use(express.logger(function(tokens, req, res) {
  if (res.statusCode === 200 || res.statusCode >= 400) // or whatever you want logged
    return formatter(tokens, req, res);
  return null;
}));

The compile() is taken from connect/lib/middleware/logger.js, it sadly isn't exported so can't be used externally, hence I copied it. You could also take the function it generates and use that directly, of course, but this way you can easily switch logging formats.

Upvotes: 1

Related Questions