From db53ef54c4ba0c7cf25ceb4ce145bc791339bb6d Mon Sep 17 00:00:00 2001 From: Thomas Kaul <4159106+dtslvr@users.noreply.github.com> Date: Wed, 30 Oct 2024 21:39:51 +0100 Subject: [PATCH] Feature/use log levels to conditionally log prisma query events (#4003) * Use LOG_LEVELS for prisma query events * Update changelog --- CHANGELOG.md | 4 ++++ apps/api/src/services/prisma/prisma.module.ts | 5 ++-- .../api/src/services/prisma/prisma.service.ts | 24 ++++++++++++++++++- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 750e733d3..44db5ad5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +### Added + +- Added support for log levels (`LOG_LEVELS`) to conditionally log `prisma` query events (`debug` or `verbose`) + ### Changed - Restructured the resources page diff --git a/apps/api/src/services/prisma/prisma.module.ts b/apps/api/src/services/prisma/prisma.module.ts index 3875c8cab..24da61047 100644 --- a/apps/api/src/services/prisma/prisma.module.ts +++ b/apps/api/src/services/prisma/prisma.module.ts @@ -1,9 +1,10 @@ import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { Module } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; @Module({ - providers: [PrismaService], - exports: [PrismaService] + exports: [PrismaService], + providers: [ConfigService, PrismaService] }) export class PrismaModule {} diff --git a/apps/api/src/services/prisma/prisma.service.ts b/apps/api/src/services/prisma/prisma.service.ts index e99d6ecf9..4673cbd19 100644 --- a/apps/api/src/services/prisma/prisma.service.ts +++ b/apps/api/src/services/prisma/prisma.service.ts @@ -1,16 +1,38 @@ import { Injectable, Logger, + LogLevel, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; -import { PrismaClient } from '@prisma/client'; +import { ConfigService } from '@nestjs/config'; +import { Prisma, PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { + public constructor(configService: ConfigService) { + let customLogLevels: LogLevel[]; + + try { + customLogLevels = JSON.parse( + configService.get('LOG_LEVELS') + ) as LogLevel[]; + } catch {} + + const log: Prisma.LogDefinition[] = + customLogLevels?.includes('debug') || customLogLevels?.includes('verbose') + ? [{ emit: 'stdout', level: 'query' }] + : []; + + super({ + log, + errorFormat: 'colorless' + }); + } + public async onModuleInit() { try { await this.$connect();