![](/img/trans.png)
[英]NestJS How to add custom Logger to custom ExceptionFilter
[英]Use custom logger in global validators
這里是 nestJS 世界的新手,我正在嘗試使用我已經在我的 nest 應用程序中使用的自定義記錄器。
這是我用來創建應用程序的代碼
async function bootstrap() {
try {
const app = await NestFactory.create(AppModule, {
bufferLogs: true,
});
const logger = app.get(CustomLogger);
app.useLogger(logger);
app.useGlobalPipes(new CustomValidationPipe());
}
如何在我的 CustomValidationPipe 中使用我的自定義記錄器?
要在 CustomValidationPipe 中使用自定義記錄器,您可以將自定義記錄器作為構造函數參數注入到 CustomValidationPipe class 中。在您的 AppModule 中,您可以將自定義記錄器添加為提供程序並使其可用於注入。 這是一個例子:
@Injectable()
export class CustomValidationPipe implements PipeTransform {
constructor(private readonly logger: CustomLogger) {}
transform(value: any, metadata: ArgumentMetadata) {
// Use the logger inside your pipe implementation here.
this.logger.log(`Value being transformed: ${value}`);
...
}
}
@Module({
providers: [CustomValidationPipe, CustomLogger],
})
export class AppModule {}
在您的引導程序 function 中,您可以繼續使用您的自定義記錄器,如您的代碼所示:
async function bootstrap() {
try {
const app = await NestFactory.create(AppModule, {
bufferLogs: true,
});
const logger = app.get(CustomLogger);
app.useLogger(logger);
app.useGlobalPipes(new CustomValidationPipe());
} catch (error) {
...
}
}
這樣,您的自定義記錄器就可以在您的 CustomValidationPipe 中使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.