우리가 작성한 코드


  1. logging 디렉토리 생성

    1. winston logger 생성 파일
    2. logging interceptor 정의 파일
      1. 각 라우터 핸들러마다 중복되는 로그 코드를 제거하기 위해 인터셉터로 구현함
  2. winston logger로 커스텀 로거 작성

  3. winston logger를 사용하는 loggingInterceptor 작성

    1. HTTP 요청과 응답을 모두 로그로 남김
    @Injectable()
    export class LoggingInterceptor implements NestInterceptor {
      intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const req = context.switchToHttp().getRequest();
        const { method, url, body } = req;
        winstonLogger.log(
          `Request to ${method} ${url}\\nbody: ${JSON.stringify(body)}`
        );
    
        return next
          .handle()
          .pipe(
            tap((data) =>
              winstonLogger.log(
                `Response from ${method} ${url}\\nresponse: ${JSON.stringify(data)}`
              )
            )
          );
      }
    }
    
  4. main.ts : LoggingInterceptor를 전역 인터셉터로 등록

    1. 전역 인터셉터로 등록하지 않으면, 각 컨트롤러나 라우터 핸들러에 @UseInterceptor() 데코레이터를 작성해줘야 한다.
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      **app.useGlobalInterceptors(new LoggingInterceptor());**
      await app.listen(3000);
    }
    

로깅 관련 To do


상황

해결 방법