Adding a hook to globally log all node HTTP responses in node.js / express
Problem
I'm using node.js and express to handle HTTP requests and responses. By using the http.ServerRequest 'request' event, I can add a hook in and log HTTP requests. There doesn't seem to be a similiar event for http.ServerResponse and I am wondering how to log all the HTTP responses with one piece of code that my server sends?
Solution
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 wrap
var rEnd = res.end;
// To track response time
req._rlStartTime = new Date();
// Proxy the real end function
res.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.
Discussion
View additional discussion.