I'm using node.js and express to handle HTTP requests and responses. By using the http.ServerRequest
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With