From 52d31fa41b1574bbbbfff1243f9e24055d4f7328 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 9 Nov 2023 10:09:56 -0600 Subject: [PATCH] Add Configure Client To Log SQL Queries as a Prisma TIL --- README.md | 3 +- prisma/configure-client-to-log-sql-queries.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 prisma/configure-client-to-log-sql-queries.md diff --git a/README.md b/README.md index db1e101..2d76165 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1347 TILs and counting..._ +_1348 TILs and counting..._ --- @@ -760,6 +760,7 @@ _1347 TILs and counting..._ - [Apply Separate Formatting With A Blank Line](prisma/apply-separate-formatting-with-a-blank-line.md) - [Batch Insert Records With createMany](prisma/batch-insert-records-with-create-many.md) +- [Configure Client To Log SQL Queries](prisma/configure-client-to-log-sql-queries.md) - [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md) - [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md) - [Open Connections To Multiple Databases](prisma/open-connections-to-multiple-databases.md) diff --git a/prisma/configure-client-to-log-sql-queries.md b/prisma/configure-client-to-log-sql-queries.md new file mode 100644 index 0000000..d40bcce --- /dev/null +++ b/prisma/configure-client-to-log-sql-queries.md @@ -0,0 +1,30 @@ +# Configure Client To Log SQL Queries + +During development, especially while debugging, it can be helpful to see the +actual SQL queries generated by Prisma queries we are formulating. Because an +ORM is an abstraction over SQL, it isn't always obvious what the resulting SQL +will turn out to be. + +By adding the `log` configuration to where we initialize our Prisma client, we +can tell it to log things like errors and the SQL of the queries it executes. + +```javascript +export const prisma = + new PrismaClient({ + log: ['error', 'query'] + }) +``` + +If we only want the SQL logged in development, we could do something like this: + +```javascript +export const prisma = + new PrismaClient({ + log: + process.env.NODE_ENV === 'development' + ? ['query', 'error'] + : ['error'], + }) +``` + +[source](https://github.com/prisma/prisma/discussions/3967)