Skip to content

Instantly share code, notes, and snippets.

@indeyets
Last active February 3, 2016 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indeyets/e26e1399cdc499f6e634 to your computer and use it in GitHub Desktop.
Save indeyets/e26e1399cdc499f6e634 to your computer and use it in GitHub Desktop.
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