How to access to the query response time?

Hi everyone,

In these days of testing I noticed that in the development environment Strapi logs the time it took to generate an api response to the console. I think this is very useful also in production and I would like to keep track of these logs, or maybe save them somewhere (most likely on the same db) for a further analysis. How can I access this information (basically, where does this log come from).

Thank you

Hello @mijorus

Create a custom middleware under: ./middlewares/storeResponseTime/index.js with the following code:

'use strict';
module.exports = strapi => {
  return {
    initialize() {
      strapi.app.use(async (ctx, next) => {
        const start = Date.now();

        await next();

        const delta = Math.ceil(Date.now() - start);
        
        //Generate the log here.
        let responseTimeLog = {
          url: ctx.request.url, 
          method:ctx.request.method,
          responseTime: delta, //response time
        };
        //Create a custom service that stores your log.
        // *responseTimeLog* look like this now:
        // { url: '/orders', method: 'GET', time: 16 }
        strapi.services.logs.responseTime.create(responseTimeLog);
      });
    },
  };
};

Modify/create the ./config/middleware.js file and add newly created middleware to it.

module.exports = {
  load: {
    //added it here
    before: ['storeResponseTime', 'responseTime', 'logger', 'cors', 'responses', 'gzip'],
    order: ["Define the middlewares' load order by putting their name in this array is the right order"],
    after: ['parser', 'router'],
  },
  settings: {
    //enable it
    storeResponseTime: {
      enabled: true,
    },
  },
};

Also, you can notice that it is returned with headers by default by responseTime middleware.
image

thank you! this is exactly what i was looking for

oh dear, it was in the docs as an example, was it?

Yes, in the documentation there is an example on how to create a custom Middleware called “timer”(identical to responseTime) . That’s the same example, I’ve just added the part with custom service and log object.

1 Like