Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import chalk from 'chalk';
const colored = function(fn) {
return function() {
var enabled = chalk.enabled;
chalk.enabled = true;
fn.apply(this, arguments);
chalk.enabled = enabled;
}
};
export default function(knex, options) {
const koaLogger = async (ctx, next) => {
const queries = [];
const captureQueries = (builder) => {
const startTime = process.hrtime();
const group = []; // captured for this builder
builder.on('query', (query) => {
group.push(query);
queries.push(query);
});
builder.on('end', () => {
// all queries are completed at this point.
// in the future, it'd be good to separate out each individual query,
// but for now, this isn't something that knex supports. see the
// discussion here for details:
// https://github.com/tgriesser/knex/pull/335#issuecomment-46787879
const diff = process.hrtime(startTime);
const ms = diff[0] * 1e3 + diff[1] * 1e-6;
group.forEach((query) => {
query.duration = ms.toFixed(3);
});
});
};
const logQueries = colored(() => {
queries.forEach((query) => {
var color = chalk.cyan;
console.log('%s %s %s %s',
chalk.gray('SQL'),
color(query.sql),
chalk.gray('{' + query.bindings.join(', ') + '}'),
chalk.magenta(query.duration + 'ms'));
});
});
knex.client.on('start', captureQueries);
await next();
knex.client.removeListener('start', captureQueries);
logQueries();
}
return koaLogger
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment