prisma-client-extensions icon indicating copy to clipboard operation
prisma-client-extensions copied to clipboard

query-logging not work in nestjs with prisma service

Open tastafur opened this issue 5 months ago • 0 comments

I have tried to use the extension in the service but it never logs information and I have tried to put it as your example and as the documentation but my loguer of the queries with the events on yes

const options = {
  log: [
    { emit: 'event', level: 'query' } as const,
    { emit: 'event', level: 'info' } as const,
    { emit: 'event', level: 'warn' } as const,
    { emit: 'event', level: 'error' } as const,
  ],
  errorFormat:
    process.env.NODE_ENV === 'production'
      ? ('minimal' as const)
      : ('pretty' as const),
};

@Injectable()
export class PrismaService
  extends PrismaClient<typeof options>
  implements OnModuleInit, OnModuleDestroy
{
  private readonly _logger = new Logger(PrismaService.name);

  public constructor() {
    super(options);
    this.$on('query', (e: Prisma.QueryEvent) => {
      console.log(e);
    });
    this.$on('info', (e: Prisma.LogEvent) => {
      this._logger.log(e.message);
    });
    this.$on('warn', (e: Prisma.LogEvent) => {
      this._logger.warn(e.message);
    });
    this.$on('error', (e: Prisma.LogEvent) => {
      this._logger.error(e.message);
    });

    this.$extends({
      query: {
        $allModels: {
          async $allOperations({ operation, model, args, query }) {
            const start = performance.now();
            const result = await query(args);
            const end = performance.now();
            const time = end - start;
            console.log(
              util.inspect(
                { model, operation, args, time },
                { showHidden: false, depth: null, colors: true },
              ),
            );
            return result;
          },
        },
      },
    });
  }
  async onModuleInit() {
    await this.$connect();
  }

  async onModuleDestroy() {
    await this.$disconnect();
  }

  async enableShutdownHooks(app: INestApplication) {
    process.on('beforeExit', async () => {
      await app.close();
    });
  }
}

tastafur avatar Feb 02 '24 09:02 tastafur