Created
June 10, 2015 18:27
-
-
Save JasonCust/2366309abf8788d24333 to your computer and use it in GitHub Desktop.
Simple Express logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function log(req, res, next) { | |
var start = process.hrtime(); | |
var write = res.write; | |
var end = res.end; | |
var chunks = []; | |
res.write = function newWrite(chunk) { | |
chunks.push(chunk); | |
write.apply(res, arguments); | |
}; | |
res.end = function newEnd(chunk) { | |
if (chunk) { chunks.push(chunk); } | |
end.apply(res, arguments); | |
}; | |
function logIt() { | |
var diff = process.hrtime(start); | |
console.log({ | |
date: new Date(), | |
duration: diff[0] * 1e9 + diff[1], | |
reqBody: req.body, | |
resBody: Buffer.concat(chunks).toString('utf8'), | |
path: req.originalUrl || req.url, | |
method: req.method, | |
status: res.statusCode | |
}); | |
} | |
res.once('finish', logIt); | |
next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment