Skip to content

Instantly share code, notes, and snippets.

@fahmifan
Last active August 25, 2023 04:14
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 fahmifan/e34bbdbcd06577fc8db7ca018f04e822 to your computer and use it in GitHub Desktop.
Save fahmifan/e34bbdbcd06577fc8db7ca018f04e822 to your computer and use it in GitHub Desktop.
How to log slow prisma query, tested on Prisma 3
const prismaClient = new PrismaClient({
log: ['query'] // must enable this to log
});
// Log slow query with all parameters in place,
// so you can copy pasted it and do EXPLAIN query
prismaClient.$on('query' as any, (e: any) => {
const dur = Number.parseInt(e?.duration);
const maxQueryTime = 100; // in ms
if (dur <= maxQueryTime) return;
console.debug('PRISMA SLOW QUERY >>>', {
duration: dur,
query: replaceQuestionMarks(e?.query, e?.params)
});
});
function replaceQuestionMarks(query: string, args: string): string {
// add quotes to date
const queryParamsArray = args.replace(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC)/g, (match) => {
return `"${match}"`;
});
const paramObjs = JSON.parse(queryParamsArray);
let replacedQuery = query;
for (const arg of paramObjs) {
if (typeof arg === 'number') {
replacedQuery = replacedQuery.replace('?', `${arg}`);
continue;
}
replacedQuery = replacedQuery.replace('?', `'${arg}'`);
}
return replacedQuery;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment