Measuring request time


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.


Up (need help please)


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


@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 :


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


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

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

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

module.exports = RequestCollectorProvider


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


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

const serverMiddleware = [


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?


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


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?