How to implement logging on nestjs?
liunian321 opened this issue · comments
Prisma Example:
const prisma = new PrismaClient({
log: [
{ level: 'warn', emit: 'event' },
{ level: 'info', emit: 'event' },
{ level: 'error', emit: 'event' },
],
})
prisma.$on('warn', (e) => {
console.log(e)
})
MyDemo:
export class PrismaProvider extends PrismaClient implements OnModuleInit {
constructor() {
super({
log: [
{ level: 'query', emit: 'event' },
{ level: 'warn', emit: 'event' },
{ level: 'info', emit: 'event' },
{ level: 'error', emit: 'event' },
],
});
}
async onModuleInit() {
await this.$connect();
}
async enableShutdownHooks(app: INestApplication) {
this.$on('info', (e) => {
console.log(e);
});
this.$on('beforeExit', async () => {
await app.close();
});
}
}
but...
error TS2345: Argument of type '"info"' is not assignable to parameter of type '"beforeExit"'.
Hey,
I created a small snippet you could use to log Prisma Client events on your console. In the example:
- I've provided
PrismaClientOptions
as a generic and the query events that would be made available to the service - I then extended the default logger from Nestjs to label the service's events
- The service can then logs out the query events whenever Prisma Client is initialized in
onModuleInit
. You can define more query events in there such asinfo
,warn
anderror
.
I'm not experienced with NestJs but this worked for me. I could be wrong. Feel free to correct me if I am. 🙂
import { Injectable, OnModuleInit, INestApplication, Logger } from '@nestjs/common'
import { Prisma, PrismaClient } from '@prisma/client'
@Injectable()
export class PrismaService extends PrismaClient<Prisma.PrismaClientOptions, 'query' | 'error' | 'info' | 'warn'>
implements OnModuleInit {
private readonly logger = new Logger(PrismaService.name);
constructor() {
super({
log: [
{ level: 'query', emit: 'event' },
{ level: 'warn', emit: 'event' },
{ level: 'info', emit: 'event' },
{ level: 'error', emit: 'event' },
],
});
}
async onModuleInit() {
this.$on('query', (event) => {
this.logger.log(event);
});
/**
* define other query events here
*/
await this.$connect();
}
async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}
I hope this helps. Don't hesitate to reach out if you have any further questions on the subject.