Search code examples
typescriptloggingnestjswinston

How to call Logger service from main.ts in NestJS?


As you can see, the assembly of the entire application occurs at the time of creation and the call to the asynchronous NestFactory.create function. In this regard, I would like to know if there is any way to call your logger inside this function and ask it to catch errors. Now I'm using a regular console.

const start = async () => {
  try {
    const PORT = process.env.PORT || 5000;
    const app = NestFactory.create(AppModule, { cors: true });
    (await app).listen(PORT, () => {
      console.log(`server started on port ${PORT}`);
    });
  } catch (error) {
    console.log(error);
  }
};

start();

But I created the WinstonLoggerModule to log entire Application and services events.

@Module({})
export class WinstonLoggerModule {
  static forRoot(): DynamicModule {
    return {
      imports: [
        WinstonModule.forRoot({
          transports: [
            new winston.transports.Console({
              format: winston.format.combine(
                winston.format.timestamp(),
                winston.format.ms(),
                nestWinstonModuleUtilities.format.nestLike('MyApp', {
                  colors: true,
                  prettyPrint: true,
                }),
              ),
            }),
      ],
      module: WinstonLoggerModule,
      providers: [
        { provide: WINSTON_LOGGER_SERVICE, useClass: WinstonLoggerService },
      ],
      exports: [WinstonLoggerModule],
    };
  }
}

And the Service as well it's based on Winsto Logger Provider.

@Injectable()
export class WinstonLoggerService implements IWinstonLoggerService {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

  warn(message): void {
    this.logger.warn(message);
  }

  error(message): void {
    this.logger.error(message);
  }

  debug(message): void {
    this.logger.debug(message);
  }

  info(message): void {
    this.logger.info(message);
  }
}

Solution

  • You can use Dependency Injection like so:

    const customLogger = app.get(WinstonLoggerService)
    app.useLogger(customLogger);
    
    (await app).listen(PORT, () => {
          customLogger.log(`server started on port ${PORT}`);
    });
    

    Refer to NestJS Documentation