【问题标题】:How to print time taken for SQL query to execute in loopback console?如何打印 SQL 查询在环回控制台中执行的时间?
【发布时间】:2019-03-30 20:43:36
【问题描述】:

我正在使用以下代码打印在我的应用程序中执行的 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 中实现这一点?

【问题讨论】:

    标签: orm loopbackjs loopback


    【解决方案1】:

    恐怕 LoopBack 不提供开箱即用的计时信息。您可以使用before executeafter execute 钩子自己收集计时数据。

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

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 1970-01-01
      • 2016-02-22
      • 2016-01-10
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多