Skip to content

Instantly share code, notes, and snippets.

@JasonCust
Created June 10, 2015 18:27
Show Gist options
  • Save JasonCust/2366309abf8788d24333 to your computer and use it in GitHub Desktop.
Save JasonCust/2366309abf8788d24333 to your computer and use it in GitHub Desktop.
Simple Express logger
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