NestJS를 사용한 자바스크립트 앱의 로깅 및 통합 모니터링 방법

자바스크립트 애플리케이션을 개발할 때 로깅 및 통합 모니터링 기능은 매우 중요합니다. 이를 통해 운영 환경에서 발생하는 문제를 신속하게 식별하고 대응할 수 있습니다. 이번 글에서는 NestJS 프레임워크를 사용하여 자바스크립트 앱에서 로깅과 통합 모니터링을 어떻게 구현할 수 있는지 알아보겠습니다.

로깅

Winston 사용하기

NestJS 앱에서 로깅을 구현하기 위해 Winston 라이브러리를 많이 사용합니다. Winston은 강력한 로깅 기능을 제공하며, 다양한 전송 모듈과 함께 사용할 수 있습니다.

먼저, Winston 패키지를 설치합니다.

npm install winston

다음으로, 로깅을 위한 모듈을 생성하고 설정합니다.

import { Injectable, LoggerService } from '@nestjs/common';
import * as winston from 'winston';

@Injectable()
export class Logger implements LoggerService {
  private readonly logger: winston.Logger;

  constructor() {
    this.logger = winston.createLogger({
      level: process.env.LOG_LEVEL || 'info',
      format: winston.format.json(),
      transports: [
        new winston.transports.Console(),
        new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
        new winston.transports.File({ filename: 'logs/combined.log' }),
      ],
    });
  }

  error(message: string, trace: string) {
    this.logger.error(message, { trace });
  }

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

  log(message: string) {
    this.logger.info(message);
  }

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

위 코드에서는 LoggerService를 구현하여 error, warn, log, debug 메서드를 제공합니다. 이를 통해 애플리케이션의 다양한 로그 레벨에 맞게 로깅할 수 있습니다.

NestJS에서 이 모듈을 사용하려면 APP_PIPE 토큰을 루트 모듈에 등록해야 합니다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from './logger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useLogger(app.get(Logger));
  
  await app.listen(3000);
}
bootstrap();

이제 앱의 로깅 설정이 완료되었습니다. 필요한 위치에서 로그를 기록할 수 있습니다.

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

@Injectable()
export class MyService {
  private readonly logger = new Logger(MyService.name);

  doSomething() {
    this.logger.log('Something happened');
  }
}

통합 모니터링

로깅 이외에도 애플리케이션의 모니터링을 위해 통합 서비스를 사용할 수 있습니다. 예를 들어, Sentry는 오류 및 예외 추적, 성능 모니터링, 리포팅 등 다양한 기능을 제공하는 통합 모니터링 서비스입니다.

먼저, Sentry 패키지를 설치하고 설정합니다.

npm install @sentry/node

다음으로, Sentry를 NestJS 앱에 통합합니다.

import { Logger, Injectable, OnModuleInit } from '@nestjs/common';
import { SentryService } from '@ntegral/nestjs-sentry';

@Injectable()
export class MyService implements OnModuleInit {
  private readonly logger = new Logger(MyService.name);

  constructor(private readonly sentryService: SentryService) {}

  onModuleInit() {
    this.sentryService.init({
      dsn: process.env.SENTRY_DSN,
    });
  }

  doSomething() {
    try {
      // ...
    } catch (error) {
      this.logger.error('Something went wrong', error.stack);
      this.sentryService.captureException(error);
    }
  }
}

위 코드에서는 SentryService를 생성하고 로깅과 함께 예외를 캡처합니다. 이로써 애플리케이션에서 발생하는 오류를 Sentry에 자동으로 보낼 수 있습니다.

이제 NestJS 앱에서 로깅과 통합 모니터링 기능을 구현하는 방법에 대해 알아보았습니다. 이를 통해 애플리케이션의 안정성과 모니터링 효율성을 높일 수 있습니다.


GitHub 소스 코드

#NestJS #로깅 #통합모니터링