Last active
February 3, 2016 21:37
-
-
Save indeyets/e26e1399cdc499f6e634 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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