Measuring request time


#1

Hello
How I can measuring request time in a middleware?
I know I can do that with http-logger but I need to store time in a variable not logging it in console.


#2

Up (need help please)


#3

Maybe you can look at the code of the http-logger and see how it tracks the request time?


#4

@virk Yep, That’s what I did, but it doesn’t seem to work, everytime I try to log response.measuredTiming (in a middleware), I got undefined :

RequestCollector.js

const onFinished = require('on-finished')

class RequestCollector {
  constructor({ request, response }) {
    this._request = request
    this._response = response
    this._res = response.response
  }

  _diffHrTime (startedAt) {
    const diff = process.hrtime(startedAt)

    return ((diff[0] * 1e9) + diff[1]) / 1e6
  }

  hook () {
    const start = process.hrtime()

    onFinished(this._res, () => {
      this._response.measuredTiming = this._diffHrTime(start)
    })
  }
}

module.exports = RequestCollector

RequestCollectorProvider.js

const { ServiceProvider } = require('@adonisjs/fold')

class RequestCollectorProvider extends ServiceProvider {
  boot () {
    const HttpContext = this.app.use('Adonis/Src/HttpContext')
    const RequestCollector = require('../src')

    HttpContext.onReady(ctx => {
      const requestCollector = new RequestCollector(ctx)
      requestCollector.hook()
    })
  }
}

module.exports = RequestCollectorProvider

#5

How can you get the response time in middleware, when the response is computed after the request is over.

Simply write your own middleware, you don’t need a provider for this

adonis make:middleware LogRequest
const onFinished = require('on-finished')

class LogRequest {
  async handle ({ request, response }) {
    const start = process.hrtime()
    onFinished(response.response, function () {
      const end = process.hrtime(start)
      const diff = ((end[0] * 1e9) + end[1]) / 1e6
      console.log(diff)
    })
  }
}

#6

And stick it to Server middleware array inside start/kernel.js file

const serverMiddleware = [
  'App/Middleware/LogRequest'
]

#7

Thank you but http-logger and this middleware show different result.
As you can see :
http-logger : 2018-11-22T13:58:36.740Z - info: GET 200 /register 311ms
middleware : /register 38ms

there’s a huge difference between 311ms and 38ms :frowning:

Is this normal behaviour?


#8

Not normal for sure. Where have you registered the middleware?


#9

Ok it works now, the difference is not too big between the two, thanks!
But one last question please, is it possible to store the value in a variable or in the response object to show it to user?