Adding a hook to globally log all node HTTP responses in node.js / express Adding a hook to globally log all node HTTP responses in node.js / express express express

Adding a hook to globally log all node HTTP responses in node.js / express


I created a package that does such a thing, out of a similar need. Check out express-request-logger

The heart of the program is like this, it contains some extra code so you can have your own key-value map of data that gets logged per request:

// Save the real end that we will wrapvar rEnd = res.end;// To track response timereq._rlStartTime = new Date();// Proxy the real end functionres.end = function(chunk, encoding) {  // Do the work expected  res.end = rEnd;  res.end(chunk, encoding);  // And do the work we want now (logging!)  // Save a few more variables that we can only get at the end  req.kvLog.status = res.statusCode;  req.kvLog.response_time = (new Date() - req._rlStartTime);  // Send the log off to winston  var level = req.kvLog._rlLevel;  delete req.kvLog._rlLevel;  logger.log(level, '', req.kvLog);};

The above code runs as middleware in express. Take a look at the code, and if you have further questions, get in touch with me on here or github.


It is no longer needed to monkeypatch, as long as there is a finish event emitted on end() function since node.js 0.8.12.

Actually, it was initially published as end in 0.8.8 (check also this) but it broke writable streams' duplexes, so it was renamed to finish.


If you only want to log (requests and/or responses), check out express-winston. Unlike morgan, it can even log the request/response body.

Example in coffeescript:

expressWinston.requestWhitelist.push('body')expressWinston.responseWhitelist.push('body')app.use(expressWinston.logger({      transports: [        new winston.transports.Console({          json: true,          colorize: true        })      ],      meta: true, // optional: control whether you want to log the meta data about the request (default to true)      msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"      expressFormat: true, // Use the default Express/morgan request formatting, with the same colors. Enabling this will override any msg and colorStatus if true. Will only output colors on transports with colorize set to true      colorStatus: true, // Color the status code, using the Express/morgan color palette (default green, 3XX cyan, 4XX yellow, 5XX red). Will not be recognized if expressFormat is true      ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response    }));