简体   繁体   English

NodeJS/Express 中的时间请求

[英]Time requests in NodeJS/Express

What would be the best way to time all requests coming into my node app?对进入我的节点应用程序的所有请求进行计时的最佳方法是什么? Basically I want to get the current timestamp at the very beginning of the request and then again at the very end of the request, get the difference and log it.基本上我想在请求的最开始获取当前时间戳,然后在请求的最后再次获取差异并记录下来。 Recommendations on the best way to do this in NodeJS and Express?关于在 NodeJS 和 Express 中执行此操作的最佳方法的建议?

Here is a sample of what my app looks like (although a lot more complex than this).这是我的应用程序的示例(尽管比这复杂得多)。

var express = require('express'),
    http = require('http'),
    app = express();

app.get('/', function (req, res, next) {
    res.send(200, 'hi');
});

app.get('/about', function(req, res, next) {
   res.send(200, 'something else');
});

var server = http.createServer(app);
server.listen(9000);
console.log("Express server listening...");

I want to time ALL requests.我想为所有请求计时。 So I want to time / and /about and anything other endpoint I might add.所以我想计时//about以及我可能添加的任何其他端点。

This might do the trick: http://www.senchalabs.org/connect/responseTime.html这可能会奏效: http : //www.senchalabs.org/connect/responseTime.html

app.use(express.responseTime());

Or do something like this:或者做这样的事情:

app.use(function(req, res, next) { req.start = Date.now(); next(); });

app.get(...);
app.get(...);

app.use(function(req, res) { var time = Date.now() - req.start; });

This requires that all your routes call next() .这要求您的所有路由都调用next()

Or maybe this (same thing as responseTime middleware, but doesn't set a header):或者这可能(与 responseTime 中间件相同,但不设置标头):

app.use(function(req, res, next) {
    var start = Date.now();
    res.on('header', function() {
        var duration = Date.now() - start;
        // log duration
    });
    next();
});

header event is fired by Connect middleware in express which is removed as of version 4. Follow this answer for solution - https://stackoverflow.com/a/27348342/4969957标头事件由 Express 中的 Connect 中间件触发,该中间件从版本 4 起已删除。按照此答案获取解决方案 - https://stackoverflow.com/a/27348342/4969957

Instead of listening for the 'header' event on res which fires once the headers are sent, you can listen for the 'finish' event, depending on what you want to measure.您可以根据要测量的内容监听'finish'事件,而不是监听res上的'header'事件,该事件会在发送标头后触发。

You can use the built-inconsole.time and console.timeEnd functions for this:您可以为此使用内置的console.timeconsole.timeEnd函数:

console.time('handler name');
... handle the request
console.timeEnd('handler name');

Output to console:输出到控制台:

handler name: 62ms

you can add to your middleware the module morgan and use it like this-您可以将模块morgan添加到您的中间件中并像这样使用它-

const morgan = require('morgan')
...
...
const app = express()
app.use(morgan('dev'))

Then the logs will look like this:然后日志将如下所示:

// :method :url :status :response-time ms - :res[content-length]
GET /myroute 200 339.051 ms - 242

Check morgan :)检查摩根:)

Or if you want a bigger time resolution you could use process.hrtime() or use a module I've build that uses hrtime but gives you a lot of extra info like average, median, total time etc. the module is called exectimer .或者,如果您想要更大的时间分辨率,您可以使用process.hrtime()或使用我构建的模块,该模块使用 hrtime 但为您提供了许多额外信息,例如平均值、中值、总时间等。该模块称为exectimer This is an example:这是一个例子:

var t = require("exectimer");

app.use(function(req, res, next) {
  var tick = new t.Tick("responseTime");
  tick.start();
  res.on('header', function() {
    tick.stop();
  });
  next();
});

// when ready check the results with this:
var responseTime = t.timers.responseTime;
console.log(responseTime.min()); // minimal response time
console.log(responseTime.max()); // minimal response time
console.log(responseTime.mean()); // mean response time
console.log(responseTime.median()); // median response time

It is very accurate and has a resolution of nanoseconds and no extra dependencies.它非常准确,分辨率为纳秒级,没有额外的依赖性。

Just get the current time in milliseconds (eg via new Date() ) when you first get a handle on the request and then the time when you finish the response and take the difference as the elapsed time in milliseconds.当您第一次获得请求的句柄时,只需获得以毫秒为单位的当前时间(例如通过new Date() ),然后是完成响应的时间,并将差值作为经过的时间(以毫秒为单位)。

http.createServer(function(req, res) {
  res.timeStart = new Date();
  // ...
  res.end(...);
  var timeStop = new Date();
  console.log('Elapsed ' + (timeStop-req.timeStart) + 'ms');
});

Note that you can subtract dates since Date#valueOf() returns their time in milliseconds.请注意,您可以减去日期,因为Date#valueOf()以毫秒为单位返回它们的时间。

I guess that the response-time middleware for express, is the one mentioned by Trevor Dixon on the first answer.我想 express 的响应时间中间件是 Trevor Dixon 在第一个答案中提到的那个。 It now allows you to set a callback to get hold of the response time, in case you don't need to set the X-Response-Time header on your response.它现在允许您设置回调以获取响应时间,以防您不需要在响应中设置 X-Response-Time 标头。 https://github.com/expressjs/response-time#responsetimefn https://github.com/expressjs/response-time#responsetimefn

export const measureRequestDuration = (req, res, next) => {
const start = Date.now();
res.once('finish', () => {
    const duration = Date.now() - start; 
    console.log("Time taken to process " + req.originalUrl + " is: " + 
  duration);
   });
 next();
};

And then然后

app.use(measureRequestDuration);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM