NodeJS/Express 中的时间请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18538537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:28:03  来源:igfitidea点击:

Time requests in NodeJS/Express

node.jsexpress

提问by tbeauvais

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 /aboutand anything other endpoint I might add.

我想为所有请求计时。所以我想计时//about以及我可能添加的任何其他端点。

回答by Trevor Dixon

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();
});

headerevent 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 reswhich fires once the headers are sent, you can listen for the 'finish'event, depending on what you want to measure.

相反监听的'header'事件res其闪光一次,头被发送,您可以监听'finish'事件,这取决于你想要什么来衡量。

回答by JohnnyHK

You can use the built-in console.timeand console.timeEndfunctions for this:

您可以为此使用内置console.timeconsole.timeEnd函数:

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

Output to console:

输出到控制台:

handler name: 62ms

回答by DavidA

you can add to your middleware the module morganand 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:)

检查摩根:)

回答by Alexandru Savin

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. This is an example:

或者,如果您想要更大的时间分辨率,您可以使用process.hrtime()或使用我构建的模块,该模块使用 hrtime 但为您提供了许多额外信息,例如平均值、中值、总时间等。该模块称为exectimer。这是一个例子:

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.

它非常准确,分辨率为纳秒级,没有额外的依赖性。

回答by Carlos

I guess that the response-time middleware for express, is the one mentioned by Trevor Dixon on the first answer. 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. https://github.com/expressjs/response-time#responsetimefn

我想 express 的响应时间中间件是 Trevor Dixon 在第一个答案中提到的那个。它现在允许您设置回调以获取响应时间,以防您不需要在响应中设置 X-Response-Time 标头。https://github.com/expressjs/response-time#responsetimefn

回答by maerics

Just get the current time in milliseconds (e.g. 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()当您第一次获得请求的句柄时,只需获得以毫秒为单位的当前时间(例如 via ),然后是完成响应的时间,并将差值作为经过的时间(以毫秒为单位)。

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()以毫秒为单位返回时间。