如何解决如何使用中间件获取Node.js中REST API的执行时间获得响应的时间和api
我想获取节点js在服务器上运行的每个api的剩余api的执行时间(获得响应的时间),它们的最后执行时间和api执行时间。
解决方法
在第一个路线之前,添加一个新的中间件,它将为您记录时间。
function logResponseTime(req,res,next) {
// Get the start time before it hits the route
const startHrTime = process.hrtime.bigint();
// Finish is emitted when the response is sent
res.on("finish",() => {
// Get the end time
const endHrTime = process.hrtime.bigint();
// Calculate the time in ms and log it
const elapsedTimeInMs = Number(endHrTime - startHrTime) / 1000000.0;
logger.info(req.method + " " + req.originalUrl + " " + elapsedTimeInMs);
});
next();
}
// Add in as middleware. Needs to be before any routes
app.use(logResponseTime);
这将记录如下内容:
GET https://my.url.com/ 180.3567
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。