Last active
August 29, 2015 14:15
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
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