Skip to content

Instantly share code, notes, and snippets.

@totherik
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totherik/b8a9a37d65950193e721 to your computer and use it in GitHub Desktop.
Save totherik/b8a9a37d65950193e721 to your computer and use it in GitHub Desktop.
import finished from 'on-finished';
let counts;
function reset() {
counts = {
/*
Synthesized properties...
http_200: 0,
http_300: 0,
http_400: 0,
http_500: 0,
...
*/
'total_requests': 0,
'current_requests': 0,
'errors': 0
};
}
function range(n) {
return ((n / 100) | 0) * 100;
}
function inc(counter) {
let count = counts[counter];
if (!count || count === Number.MAX_SAFE_INTEGER) {
count = 1;
} else {
count += 1;
}
counts[counter] = count;
}
function dec(counter) {
if (counter in counts) {
counts[counter] -= 1;
}
}
export default function ({ interval = 5 * 1000 }) {
let app, server;
setInterval(() => {
if (app) {
app.emit('stats', counts);
reset();
}
}, interval).unref();
reset();
return function (req, res, next) {
{ app } = req;
if (!server) {
// Add instrumentation to get response times. There
// is a caveat that we won't record the very first request,
// but I'm ok with that tradeoff since we guarantee accurate
// request times due to not relying on middleware ordering.
{ socket: { server } } = req;
server.on('request', function (req, res) {
let start = Date.now();
finished(res, () => {
let duration = Date.now() - start;
// do something with duration
});
});
}
inc('total_requests');
inc('current_requests');
finished(res, (err, res) => {
if (err) {
inc('errors');
}
inc('http_' + range(res.statusCode | 0));
dec('current_requests');
});
next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment