Rails(ActiveRecord)ではクエリの実行時間や内容がわかりやすくログに表示されている。
sequelizeでログをカスタムしてそれっぽくする。
ログのカスタム
以下の記事参考
https://qiita.com/TsuyoshiMIYAMOTO/items/ba755b91789f9888f8e2
カスタムログで実行時間を取得する
sequelizeにはbenchmarkオプションがあり、
var sequelize = new Sequelize(db, username, password, {
benchmark: true
})
のように全体で設定するか、
const users = await User.findAll({benchmark: true})
のように各クエリで設定する。
実行時間はloggingの関数の第2引数で渡される。
var sequelize = new Sequelize(db, username, password, {
benchmark: true,
logging: (logStr, execTime, options) => {
logger.debug(logStr, execTime)
}
})
最終例
いい感じに色を設定
const colors = require('colors/safe')
const path = require('path')
const env = process.env.NODE_ENV || 'development'
const config = require(path.resolve('config', 'database.json'))[env]
const options = Object.assign({}, config, {
logging: (logStr, execTime, options) => {
if (!options) {
options = execTime
execTime = undefined
}
let col = null
switch (options.type) {
case 'SELECT':
col = colors.blue.bold
break
case 'UPDATE':
col = colors.yellow.bold
break
case 'INSERT':
col = colors.green.bold
break
default:
col = colors.white.bold
break
}
if (execTime) {
logger.debug(colors.magenta.bold(`[${execTime} ms]`), col(logStr))
} else {
logger.debug(col(logStr))
}
}
})
const sequelize = new Sequelize(config.database, config.username, config.password, options)