DB Query Logging with Request Context

I'm wanting my DB queries to be logged using structured JSON and including the trace id of the request that caused the query to run. Previously I had a single global drizzle instance that I imported directly in my handlers. In order to support tracing I've added a middleware that add's a drizzle instance per request. Every drizzle instance is initialized with the same postgres.js connection, and my handlers now use c.var.db to access the DB. Is this the expected usage pattern? Are there issues I should expect with having multiple drizzle instances using the same underlying connection?
import { connection, schema, StructuredLogQueryWriter } from "@/db";

export const dbMiddleware = createMiddleware<AppBindings>(async (c, next) => {
assert(c.var.logger, "Expected logger middleware to be called before db middleware");
const db = drizzle(connection, {
schema,
logger: new StructuredLogQueryWriter(c.var.logger),
});
c.set("db", db);

await next();
});
import { connection, schema, StructuredLogQueryWriter } from "@/db";

export const dbMiddleware = createMiddleware<AppBindings>(async (c, next) => {
assert(c.var.logger, "Expected logger middleware to be called before db middleware");
const db = drizzle(connection, {
schema,
logger: new StructuredLogQueryWriter(c.var.logger),
});
c.set("db", db);

await next();
});
1 Reply
TOSL
TOSL6d ago
It sounds logical to me. The biggest thing would have been not using the same postgres connection but already accounted for it. I've never used the custom logging so I don't know the limitations there But it's available to be used so as long of your performance isn't impacted you should just roll with whatever works for you.

Did you find this page helpful?