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?
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.
This might do the trick: 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()
.
Or maybe this (same thing as responseTime middleware, but doesn't set a header):
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
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.
You can use the built-inconsole.time
and console.timeEnd
functions for this:
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-
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 . 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.
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.
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
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.