Skip to content

Instantly share code, notes, and snippets.

@macedd
Last active February 5, 2019 05:55
Show Gist options
  • Save macedd/c118013b04e94c9348792ad50a5bf930 to your computer and use it in GitHub Desktop.
Save macedd/c118013b04e94c9348792ad50a5bf930 to your computer and use it in GitHub Desktop.
Nodejs measure execution time
async function logRouteExecTime(req, res, next) {
const startTime = process.hrtime();
res.once('finish', () => {
const endTime = parseHrtimeToSeconds(process.hrtime(startTime));
const payload = {
server_method: req.method,
server_url: `${req.baseUrl}${req.route ? req.route.path : ''}`,
server_params: req.params,
server_time: endTime,
response_code: res.statusCode,
};
console.log('logRouteExecTime', JSON.stringify(payload));
});
next();
}
// first middleware assigned
app.use(logRouteExecTime);
parseHrtimeToSeconds(hrtime, fixed = false) {
const seconds = (hrtime[0] + (hrtime[1] / 1e9));
if (fixed) {
// 3 decimals for exposing the microseconds
return seconds.toFixed(3);
}
return seconds;
}
function emitAndLogBackgroundExecTime(app, eventName, ...args) {
const startTime = process.hrtime();
function completedExecLogTime() {
const endTime = parseHrtimeToSeconds(process.hrtime(startTime));
const payload = {
background_event: eventName,
background_args: args,
server_time: endTime,
};
console.log('logBackgroundExecTime', JSON.stringify(payload));
}
// event will finish on the function bellow since that's the last listener on the event
app.once(eventName, completedExecLogTime);
try {
// emit the event on the app
app.emit(eventName, ...args);
} catch (err) {
app.off(eventName, completedExecLogTime);
completedExecLogTime();
throw err;
}
}
emitAndLogBackgroundExecTime(app, 'myEvent');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment