首页 > 解决方案 > 如何基于 env 禁用 NestJS Logger?

问题描述

我在NestFactory.create()方法中使用 logger 选项来控制生产模式下 Logger 的日志级别,但它不能使用ENV='production',仍然显示Logger.log()消息

const bootstrap = async () => {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger:
      env.ENV == 'development'
        ? ['debug', 'error', 'log', 'verbose', 'warn']
        : ['error', 'warn'],
  });

  app.enableCors();

  app.use(helmet());
  app.set('trust proxy', 1);

标签: typescriptnestjs

解决方案


  1. 我创建了我的自定义记录器
  2. 将其注入根模块。

在自定义记录器的构造函数中,我使用setLogLevels函数放置了我的条件。我将级别设置为空,因此它可以忽略任何控制台标准输出。

import { ConsoleLogger, Injectable, LoggerService } from '@nestjs/common';

@Injectable()
export class AppLogger extends ConsoleLogger implements LoggerService {
  constructor(
    context: string,
    options?: {
      timestamp?: boolean;
    },
  ) {
    super(context, options);
    /***
     * @condition to check if it is in testing mode
     */
    if (condition) {
      this.setLogLevels([]);
    }
  }
}


推荐阅读