如何打印 SQL 查询在环回控制台中执行所花费的时间?
How to print time taken for SQL query to execute in loopback console?
我正在使用以下代码打印 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 在 rails 应用程序上打印 sql 查询以及时间,类似于下面给出的
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
有什么方法可以在环回 3 中实现吗?
恐怕 LoopBack 不提供开箱即用的计时信息。您可以使用 before execute
和 after 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();
});
}
我正在使用以下代码打印 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 在 rails 应用程序上打印 sql 查询以及时间,类似于下面给出的
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
有什么方法可以在环回 3 中实现吗?
恐怕 LoopBack 不提供开箱即用的计时信息。您可以使用 before execute
和 after 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();
});
}