I'm printing SQL queries executed in my application using below code
var chalk = require('chalk');
module.exports = (app) => {
var connector = app.datasources.mysqlDs.connector;
connector.observe('after execute', function(ctx, next) {
console.log(chalk.green(ctx.req.sql));
next();
});
}
The above code prints sql query in console like this,
SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
I'm interested to print time take to execute the sql query.
Ruby on rails applications prints sql query along with timing, similar to this given below
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Is there any way to achieve this in loopback 3?
I am afraid LoopBack does not provide timing information out of the box. You can use before execute
and after execute
hooks to gather timing data yourself.
module.exports = (app) => {
var connector = app.datasources.mysqlDs.connector;
connector.observe('before execute', function(ctx, next) {
// store the start time in the context
ctx.__started = process.hrtime();
next();
});
connector.observe('after execute', function(ctx, next) {
// compute the time difference as [seconds, nanoseconds]
const delta = process.hrtime(ctx.__started);
// convert the two-part value into number of milliseconds elapsed
// and round it to a single decimal place
const durationInMs = 10 * Math.round((delta[0]*1000 + delta[1]/1e6)/10);
console.log('(%s ms) %s', durationInMs, chalk.green(ctx.req.sql));
next();
});
}