Skip to content

Instantly share code, notes, and snippets.

@masylum
Last active October 5, 2025 14:50
Show Gist options
  • Select an option

  • Save masylum/d081e4b21bf11c2d321d61f4cc8ecd89 to your computer and use it in GitHub Desktop.

Select an option

Save masylum/d081e4b21bf11c2d321d61f4cc8ecd89 to your computer and use it in GitHub Desktop.
Drizzle Rails Logger
import chalk from "chalk"
import { entityKind, type Logger } from "drizzle-orm"
import { format as formatSql } from "sql-formatter"
chalk.level = 3
function getSqlColor(sql: string) {
const normalized = sql.trim().toUpperCase()
if (normalized.startsWith("INSERT")) return "green"
if (normalized.startsWith("DELETE")) return "red"
if (normalized.startsWith("UPDATE")) return "yellow"
if (
normalized.startsWith("BEGIN") ||
normalized.startsWith("COMMIT") ||
normalized.startsWith("ROLLBACK") ||
normalized.startsWith("SAVEPOINT") ||
normalized.startsWith("RELEASE SAVEPOINT")
)
return "cyan"
return "blue"
}
export class FikaLogger implements Logger {
static readonly [entityKind]: string = "FikaLogger"
private lastQueryTime: number = Date.now()
logQuery(query: string, params: any[], label?: string): void {
const currentTime = Date.now()
const duration = currentTime - this.lastQueryTime
this.lastQueryTime = currentTime
const labelStr = label ? chalk.cyan.bold(label) : ""
const sqlColor = getSqlColor(query)
const formatParam = (param: any): string => {
if (param === null) return "NULL"
if (param === undefined) return "NULL"
if (typeof param === "string") {
const escaped = param.replace(/'/g, "''")
const truncated =
escaped.length > 100 ? `${escaped.substring(0, 100)}…` : escaped
return `'${truncated}'`
}
if (typeof param === "boolean") return param ? "TRUE" : "FALSE"
if (param instanceof Date) return `'${param.toISOString()}'`
return String(param)
}
const paramsObject = params.reduce(
(obj, param, index) => {
obj[index + 1] = chalk.underline(
chalk[`${sqlColor}Bright`](formatParam(param)),
)
return obj
},
{} as Record<number, any>,
)
const formattedSql = formatSql(query, {
language: "postgresql",
keywordCase: "upper",
expressionWidth: 100,
params: paramsObject,
})
.replace(/\s+/g, " ")
.trim()
const sqlStr = chalk.bold(chalk[sqlColor](formattedSql))
const timingStr = chalk.bold.whiteBright(`(${duration}ms)`)
const line = [timingStr, labelStr, sqlStr].filter(Boolean).join(" ")
console.log(` → ${line}`)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment