如何在NestJS中配置Prisma以在终端打印原始查询日志?
在NestJS中正确配置Prisma日志以显示原始查询
当前配置存在几处冲突和遗漏,导致终端看不到Prisma的原始查询日志,以下是修正后的完整配置方案:
核心问题分析
- 日志配置冲突:
PrismaModule.forRoot和PrismaService的super()中重复配置了日志,导致部分设置被覆盖 - 中间件未注册:自定义的日志中间件没有挂载到PrismaClient实例上
- NestJS日志级别未开启debug:代码中用了
logger.debug()输出查询,但默认日志级别可能不包含debug
修正后的配置步骤
1. 简化PrismaModule配置
移除prismaOptions中的日志配置,统一在PrismaService中设置:
PrismaModule.forRoot({ isGlobal: true, prismaServiceOptions: { explicitConnect: true, }, }),
2. 确保日志中间件注册
保持你的日志中间件代码不变,但要在PrismaService中挂载:
import { Prisma } from '@prisma/client'; export function loggingMiddleware(): Prisma.Middleware { return async (params, next) => { const before = Date.now(); const result = await next(params); const after = Date.now(); console.log(`Query ${params.model}.${params.action} took ${after - before}ms`); return result; }; }
3. 完整修正PrismaService
统一日志配置、注册中间件、监听query事件输出原始SQL:
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { INestApplication } from '@nestjs/common/interfaces'; import { Prisma, PrismaClient } from '@prisma/client'; import { loggingMiddleware } from './logging.middleware'; // 替换为你的中间件实际路径 @Injectable() export class PrismaService extends PrismaClient<Prisma.PrismaClientOptions, 'query | error | debug | info'> implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(PrismaService.name); constructor() { super({ log: [ { emit: 'event', level: 'query' }, // 将query日志触发为事件,方便监听 { emit: 'stdout', level: 'info' }, { emit: 'stdout', level: 'warn' }, { emit: 'stdout', level: 'error' }, ], errorFormat: 'colorless', }); this.logger.log(`Prisma v${Prisma.prismaVersion.client}`); // 挂载自定义日志中间件 this.$use(loggingMiddleware()); // 监听query事件,输出原始SQL、参数和执行时长 this.$on('query', (e) => { this.logger.debug(`SQL: ${e.query}`); if (e.params) { this.logger.debug(`Params: ${e.params}`); } this.logger.debug(`Duration: ${e.duration}ms`); }); } async onModuleInit() { await this.$connect(); } async onModuleDestroy() { await this.$disconnect(); } async enableShutdownHooks(app: INestApplication) { this.$on('beforeExit', async () => { await app.close(); }); } }
4. 开启NestJS的Debug日志级别
在main.ts中设置日志级别,确保能看到logger.debug()的输出:
import { Logger } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: new Logger({ level: 'debug', // 必须开启debug级别才能看到查询日志 }), }); // 启用Prisma shutdown hooks const prismaService = app.get(PrismaService); prismaService.enableShutdownHooks(app); await app.listen(3000); } bootstrap();
关键注意事项
- 不要同时在
PrismaModule和PrismaService中配置日志,避免覆盖 - 自定义中间件用于统计查询耗时,若不需要可直接移除
this.$use(loggingMiddleware()) - 如果只想在开发环境显示查询日志,可以通过环境变量控制日志级别和配置
内容的提问来源于stack exchange,提问作者penetrator.go
相关产品推荐
相关产品推荐

