Skip to content

Instantly share code, notes, and snippets.

@Deityhub
Created November 9, 2021 15:36
Show Gist options
  • Save Deityhub/1fc5f58ba826b25b9a0f60088cfa0098 to your computer and use it in GitHub Desktop.
Save Deityhub/1fc5f58ba826b25b9a0f60088cfa0098 to your computer and use it in GitHub Desktop.
Log request middleware
// log request middleware
const getActualRequestDurationInMilliseconds = start => {
const NS_PER_SEC = 1e9; // convert to nanoseconds
const NS_TO_MS = 1e6; // convert to milliseconds
const diff = process.hrtime(start);
return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS;
};
app.use(function(req, res, next) {
const current_datetime = new Date();
const formatted_date =
current_datetime.getFullYear() +
'-' +
(current_datetime.getMonth() + 1) +
'-' +
current_datetime.getDate() +
' ' +
current_datetime.getHours() +
':' +
current_datetime.getMinutes() +
':' +
current_datetime.getSeconds();
const method = req.method;
const url = req.url;
const status = res.statusCode;
const start = process.hrtime();
const durationInMilliseconds = getActualRequestDurationInMilliseconds(
start
);
const log = `[${formatted_date}] ${method}:${url} ${status} ${durationInMilliseconds.toLocaleString()} ms`;
console.log(log);
return next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment