project/NestJS + Kubernetes & 마이크로서비스 배포

📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드 - NestJS Observability: 로그, 모니터링, 추적 통합 가이드

octo54 2025. 4. 11. 10:49
반응형

📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드

10. NestJS Observability: 로그, 모니터링, 추적 통합 가이드


NestJS 애플리케이션이 안정적으로 운영되기 위해서는 단순한 로깅을 넘어, **시스템 전반을 관찰할 수 있는 구조(Observability)**를 갖추는 것이 중요합니다.
이번 글에서는 NestJS 애플리케이션에 로그 수집, 메트릭 모니터링, 분산 추적(Tracing)을 통합하는 방법을 소개합니다.


✅ 1. Observability란?

Observability(관찰 가능성)는 시스템의 상태를 외부에서 로그, 지표, 추적 데이터를 통해 이해하고 예측할 수 있는 능력을 의미합니다.

  • Logs (로그): 과거의 사건 추적
  • Metrics (지표): 현재 상태를 수치로 표시
  • Tracing (추적): 요청 흐름 및 병목 추적

💡 이 세 가지를 통합하면 복잡한 마이크로서비스 시스템을 효율적으로 운영 가능!


✅ 2. 로깅 (Structured Logging)

✅ Logger 도구: nestjs-pino, winston, pino

npm install nestjs-pino pino

📂 main.ts

import { Logger } from 'nestjs-pino';

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

📂 app.module.ts

@Module({
  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        transport: {
          target: 'pino-pretty',
          options: { colorize: true },
        },
      },
    }),
  ],
})

✅ 로그에 traceId, requestId, context 정보 포함하면 추적 가능성 향상


✅ 3. 메트릭 수집 (Prometheus + Grafana)

✅ 설치

npm install prom-client

📂 metrics.controller.ts

import { Controller, Get } from '@nestjs/common';
import { Registry, collectDefaultMetrics } from 'prom-client';

const registry = new Registry();
collectDefaultMetrics({ register: registry });

@Controller('metrics')
export class MetricsController {
  @Get()
  getMetrics() {
    return registry.metrics();
  }
}

💡 /metrics 엔드포인트를 Prometheus에서 수집 → Grafana 대시보드로 시각화


✅ 4. 분산 추적 (Distributed Tracing)

✅ OpenTelemetry 적용

npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/instrumentation-http

📂 tracing.ts

import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';

const sdk = new NodeSDK({
  serviceName: 'nestjs-app',
  instrumentations: [getNodeAutoInstrumentations()],
});

sdk.start();

📂 main.ts

import './tracing';

✅ Jaeger, Zipkin, Tempo 등으로 trace 데이터 전송 가능


✅ 5. 클라우드/클러스터 연동 (Kubernetes 기준)

항목 구현 전략

로그 집계 Fluentd or Loki + Grafana
메트릭 수집 Prometheus Helm Chart
분산 추적 시스템 Tempo, Jaeger, OpenTelemetry Collector

예: Grafana Stack 설치

helm repo add grafana https://grafana.github.io/helm-charts
helm install k-stack grafana/loki-stack
helm install grafana grafana/grafana

✅ 6. 실전 Observability 패턴

  • NestJS logger에 traceId 주입하여 trace 연결
  • Kafka / RabbitMQ / gRPC 통신 간 context 전달 (Correlation ID)
  • 각 서비스별 /health, /metrics, /logs 엔드포인트 통합
  • 에러 발생 시 로그 + trace ID 기반으로 빠르게 원인 추적

✅ 결론: NestJS 운영 환경을 관찰 가능한 시스템으로 만들기

✅ nestjs-pino로 구조적 로깅
✅ prom-client로 메트릭 수집 → Prometheus + Grafana 시각화
✅ OpenTelemetry로 trace 연결 → Jaeger/Tempo로 병목 분석
✅ Kubernetes와 완벽 연동하여 클라우드 운영 효율성 극대화

이제 NestJS 마이크로서비스는 안정성과 투명성을 갖춘 운영 시스템으로 진화합니다.
다음 글에서는 NestJS 프로젝트를 Monorepo + Nx로 구조화하고 대규모 개발 생산성을 높이는 전략을 다룹니다! 🚀


🔍 다음 글 예고: NestJS + Nx Monorepo 구조화 전략

📌 다음 편: 11. NestJS + Nx 기반 대규모 프로젝트 구조 설계


 

NestJS Observability,NestJS 로그 수집,NestJS 모니터링,NestJS Prometheus,NestJS Grafana,NestJS OpenTelemetry,NestJS 트레이싱,NestJS 메트릭 수집,NestJS Jaeger,NestJS Kubernetes 모니터링