NestJs Logger Winston 적용

까망거북·2024년 10월 22일

NestJs에 로거를 적용하기로 했다.
참고자료

모듈설치

npm install --save nest-winston winston

적용

  • 어플리케이션 실행시부터 로거를 변경하기 위하여 Replacing the Nest logger (also for bootstrapping) 방식으로 적용하기로 함
  • main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as winston from 'winston';
import {
  WinstonModule,
  utilities as nestWinstonMoluleUtilties,
} from 'nest-winston';
async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: WinstonModule.createLogger({ +
      transports: [ +
        new winston.transports.Console({ +
          level: 'silly', +
          format: winston.format.combine( +
            winston.format.timestamp(), +
            winston.format.ms(), +
            nestWinstonMoluleUtilties.format.nestLike('MyApp', { +
              colors: true, +
              prettyPrint: true, +
              processId: true, +
              appName: true, +
            }), +
          ), +
        }), +
      ],
    }),
  });

bootstrap();
  • app.module.ts
import { Logger, Module } from '@nestjs/common'; +
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService, Logger], +
})
export class AppModule {}
  • app.controller.ts
import { Controller, Get, Inject, Logger } from '@nestjs/common'; +
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly logger: Logger,
  ) {}

  @Get()
  getHello(): string {
    this.logger.error('Calling getHello()', AppController.name); +
    this.logger.fatal('Calling getHello()', AppController.name); +
    this.logger.log('Calling getHello()', AppController.name); +
    this.logger.debug('Calling getHello()', AppController.name); +
    this.logger.verbose('Calling getHello()', AppController.name); +
    this.logger.warn('Calling getHello()', AppController.name); +
    return this.appService.getHello();
  }
}
  • 결과
[MyApp] 2024. 10. 22. 오전 11:42:43   ERROR  Calling getHello() - { stack: [ 'AppController' ] } +11s
[MyApp] 2024. 10. 22. 오전 11:42:43   ERROR  Calling getHello() - { stack: [ 'AppController' ] } +1ms
[MyApp] 2024. 10. 22. 오전 11:42:43     LOG [AppController] Calling getHello() +1ms
[MyApp] 2024. 10. 22. 오전 11:42:43   DEBUG [AppController] Calling getHello() +1ms
[MyApp] 2024. 10. 22. 오전 11:42:43 VERBOSE [AppController] Calling getHello() +1ms
[MyApp] 2024. 10. 22. 오전 11:42:43    WARN [AppController] Calling getHello() +0ms

0개의 댓글