【问题标题】:NestJS How to add custom Logger to custom ExceptionFilterNestJS 如何将自定义 Logger 添加到自定义 ExceptionFilter
【发布时间】:2019-11-05 09:53:41
【问题描述】:

我正在使用 NestJS 5.4.0 我有自定义 LoggerService,它运行良好。但是,如何将此 LoggerService 添加到 ExceptionFilter。

// logger.service.ts
import {Injectable, LoggerService} from '@nestjs/common';
@Injectable()
export class Logger implements LoggerService {
    log(message: string) {
        console.log(message);
    }
    error(message: string, trace: string) {
        console.error(message);
    }
    warn(message: string) {
        console.warn(message);
    }
}

//logger.module.ts
import { Module } from '@nestjs/common';
import {Logger} from '../services/logger.service';
@Module({
    providers: [Logger],
    exports: [Logger],
})
export class LoggerModule {}


// user.module.ts
import { Module } from '@nestjs/common';
import {UserService} from '../services/user.service';
import {LoggerModule} from './logger.module';

@Module({
    imports: [LoggerModule],
    providers: [UserService],
    exports: [UserService],
})
export class UserModule {}

效果很好。

import {Logger} from './logger.service';
export class UserService {
    constructor(
        private logger: Logger
    ) {}
    private test = () => {
        this.logger.log("test"); // log success "test" to console
    }
}

但是如何将我的自定义 Logger 添加到 ExceptionFilter

// forbidden.exception.filter.ts
import {HttpException, HttpStatus, Injectable} from '@nestjs/common';

@Injectable()
export class ForbiddenException extends HttpException {
    constructor(message?: string) {
        super(message || 'Forbidden', HttpStatus.FORBIDDEN);
        // I want to add my custom logger here!
    }
}

感谢阅读。

【问题讨论】:

  • 问题的最后一部分使您看起来像是在尝试将日志记录添加到 Exception 类,因为您显示了 ForbiddenException。这是您想要完成的(即每次实例化Exception 实例时记录),还是您想使用异常过滤器? nestjs 文档提供了一个HTTPExceptionFilter 的示例:docs.nestjs.com/exception-filters
  • 那些文档没有展示如何将自定义记录器注入自定义异常过滤器。我遇到了同样的问题。

标签: node.js nest nestjs


【解决方案1】:

首先你的class ForbiddenException extends HttpException 不是 它叫什么ExceptionFilterExceptionFilter

异常层,负责处理应用程序中所有未处理的异常

docs

您在尝试将其注入自定义 HttpException 时提供了示例。但那是错误的。您的异常不必负责记录。这就是ExceptionFilter应该负责的事情。

无论如何,目前(2019 年 10 月 17 日)官方文档中没有示例如何将提供程序注入 ExceptionFilter

您可以在初始化时将其传递给constructor,但您应该先使用app.get<T>(...) 方法获取Logger 实例。

例如,我将代码从 exception-filters docs 更改为:

// HttpExceptionFilter.ts

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
import {MyLogger} from '../MyLogger'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: MyLogger) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    if (status >= 500) {
      this.logger.error({ request, response });
    }

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}

bootstrap.ts代码:

// bootstrap.ts

const app = await NestFactory.create(MainModule, {
  logger: false,
});

const logger = app.get<MyLogger>(MyLogger);
app.useLogger(logger);
app.useGlobalFilters(new HttpExceptionFilter(logger));

此技术可用于所有INestApplication 方法:

  • app.useGlobalFilters
  • app.useGlobalGuards
  • app.useGlobalInterceptors
  • app.useGlobalPipes
  • app.useLogger
  • app.useWebSocketAdapter

【讨论】:

    【解决方案2】:

    首先,要将依赖注入与异常过滤器一起使用,您不能使用useGlobalFilters() 方法注册它们:

    const app = await NestFactory.create(MainModule, {
      logger: false,
    });
    
    const logger = app.get<MyLogger>(MyLogger);
    app.useLogger(logger);
    
    //Remove this line
    //app.useGlobalFilters(new HttpExceptionFilter(logger));
    

    接下来在您的MainModule 中,将您的自定义异常过滤器添加为提供程序(注意:过滤器会自动设置为全局,无论您将它们添加到哪个模块,但作为最佳实践,请将它们添加到您的顶级模块):

    import { Module } from '@nestjs/common';
    import { APP_FILTER } from '@nestjs/core';
    import { LoggerModule } from './logger.module';
    import { ForbiddenException } from './forbidden.exception.filter.ts';
    
    @Module({
      imports: [
        LoggerModule //this is your logger module
      ],
      providers: [
        {
          provide: APP_FILTER, //you have to use this custom provider
          useClass: ForbiddenException //this is your custom exception filter
        }
      ]
    })
    export class MainModule {}
    

    现在您可以将记录器注入您的自定义异常过滤器:

    import {HttpException, HttpStatus, Injectable} from '@nestjs/common';
    import { Logger } from './path/to/logger';
    
    @Injectable()
    export class ForbiddenException extends HttpException {
    
      constructor(private logger: Logger) {}
    
      catch(exception: HttpException, response) {
        this.logger.log('test');
      }
    }
    

    伪代码,但我想你明白了。

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多