How to disable NestJS Logger, based on env?

Viewed 5084

I'm using logger option in NestFactory.create() method to control Logger's log levels in production mode, but it's not working with ENV='production', still showing Logger.log() messages

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);
2 Answers
  1. I create my custom logger
  2. Inject it in the root module.

Within the constructor of the custom logger, that is where I put my condition using the setLogLevels function. I set the levels to empty, so it can ignore any console stdout.

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([]);
    }
  }
}

Env variables are accessed with process.env global object, in Node.js.

The following example is working as expected, reading process.env.ENV:

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: process.env.ENV === 'production' ? ['warn', 'error'] : ['debug', 'log', 'verbose']
  });
  await app.listen(3000);
}

bootstrap();

yarn start display all initialization logs, whereas ENV=production yarn start shows no initialization logs.

Related