vdka
vdka
DTDrizzle Team
Created by vdka on 4/15/2025 in #help
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();
});
4 replies