Created
April 16, 2019 15:48
-
-
Save sochix/831990a5f513bb74e677cc0c4958c5b8 to your computer and use it in GitHub Desktop.
Proper way to measure request duration in a Node.js + Express application
This file contains hidden or 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
const app = require('express')() | |
const getDurationInMilliseconds = (start) => { | |
const NS_PER_SEC = 1e9 | |
const NS_TO_MS = 1e6 | |
const diff = process.hrtime(start) | |
return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS | |
} | |
app.use((req, res, next) => { | |
console.log(`${req.method} ${req.originalUrl} [STARTED]`) | |
const start = process.hrtime() | |
res.on('finish', () => { | |
const durationInMilliseconds = getDurationInMilliseconds (start) | |
console.log(`${req.method} ${req.originalUrl} [FINISHED] ${durationInMilliseconds.toLocaleString()} ms`) | |
}) | |
res.on('close', () => { | |
const durationInMilliseconds = getDurationInMilliseconds (start) | |
console.log(`${req.method} ${req.originalUrl} [CLOSED] ${durationInMilliseconds.toLocaleString()} ms`) | |
}) | |
next() | |
}) | |
// send response immediately | |
app.get('/fast/', (req, res) => { | |
res.sendStatus(200) | |
}) | |
// mock heavy load, send response after 10 seconds | |
app.get('/slow/', (req, res) => { | |
setTimeout(() => res.sendStatus(200), 10 * 1000) | |
}) | |
app.listen(3000, () => { | |
console.log('Server started') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How I use it is the
finish
event for calculating the request duration and theclose
event to log it. This way I can keep the middleware simple with only the finish event in there and somewhere else (at the end) I use the close event to log everything I need.and then somewhere else/later: