如何打印在回送控制台中执行SQL查询所花费的时间?

时间:2018-10-26 06:33:26

标签: orm loopbackjs loopback

现在,我正在使用以下代码打印在我的应用程序中执行的sql查询

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();
  });
}

上面的代码像这样在控制台中打印sql查询,

SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1

我有兴趣打印执行SQL查询所花费的时间。

Ruby on Rails应用程序将打印SQL查询以及时间,类似于下面给出的

 User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1

在环回3中有什么方法可以做到这一点?

预先感谢

1 个答案:

答案 0 :(得分:1)

恐怕LoopBack不提供开箱即用的定时信息。您可以使用after executemodule.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(); }); } 挂钩自己收集计时数据。

node_modules