icon안동민 개발노트

서버 사이드 로깅 및 모니터링


 Next.js App Router를 사용한 애플리케이션의 서버 사이드 로깅 및 모니터링은 애플리케이션의 안정성과 성능을 유지하는 데 crucial합니다. 이 절에서는 효과적인 로깅 구현 방법과 모니터링 전략에 대해 알아보겠습니다.

구조화된 로깅 구현

 Winston을 사용하여 구조화된 로깅을 구현할 수 있습니다.

  1. Winston 설치 :
npm install winston
  1. 로거 설정 :
// lib/logger.js
import winston from 'winston';
 
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'next-app' },
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' }),
  ],
});
 
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple(),
  }));
}
 
export default logger;
  1. API 라우트에서 로거 사용 :
// app/api/example/route.js
import { NextResponse } from 'next/server';
import logger from '../../../lib/logger';
 
export async function GET(request) {
  logger.info('GET request to /api/example', { 
    query: request.nextUrl.searchParams.toString() 
  });
  
  try {
    // 비즈니스 로직
    return NextResponse.json({ message: 'Success' });
  } catch (error) {
    logger.error('Error in GET /api/example', { error: error.message });
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}

로그 레벨 관리

 환경 변수를 사용하여 로그 레벨을 동적으로 관리할 수 있습니다.

// lib/logger.js
const level = process.env.LOG_LEVEL || 'info';
 
const logger = winston.createLogger({
  level: level,
  // ... 기타 설정
});

중앙 집중식 로그 수집 시스템 구축

 ELK (Elasticsearch, Logstash, Kibana) 스택을 사용하여 중앙 집중식 로그 수집 시스템을 구축할 수 있습니다.

  1. Logstash 설정 :
input {
  file {
    path => "/path/to/your/logs/*.log"
    start_position => "beginning"
  }
}

filter {
  json {
    source => "message"
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "nextjs-logs-%{+YYYY.MM.dd}"
  }
}
  1. Winston Elasticsearch 트랜스포트 추가 :
import { ElasticsearchTransport } from 'winston-elasticsearch';
 
const esTransportOpts = {
  level: 'info',
  clientOpts: { node: 'http://localhost:9200' },
  indexPrefix: 'nextjs-logs'
};
 
logger.add(new ElasticsearchTransport(esTransportOpts));

실시간 모니터링 도구 통합

 Prometheus와 Grafana를 사용하여 실시간 모니터링 시스템을 구축할 수 있습니다.

  1. Prometheus 클라이언트 설치 :
npm install prom-client
  1. 메트릭 설정 :
// lib/metrics.js
import prometheus from 'prom-client';
 
const collectDefaultMetrics = prometheus.collectDefaultMetrics;
collectDefaultMetrics({ timeout: 5000 });
 
const httpRequestDurationMicroseconds = new prometheus.Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'code'],
  buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10]
});
 
export { httpRequestDurationMicroseconds };
  1. 메트릭 엔드포인트 생성 :
// app/api/metrics/route.js
import { NextResponse } from 'next/server';
import prometheus from 'prom-client';
 
export async function GET() {
  const metrics = await prometheus.register.metrics();
  return new NextResponse(metrics, {
    headers: {
      'Content-Type': prometheus.register.contentType
    }
  });
}
  1. Grafana 대시보드 설정 :
  • Prometheus 데이터 소스 추가
  • 사용자 정의 대시보드 생성 (요청 속도, 에러율 등 시각화)

알림 시스템 설정

 Grafana 알림을 사용하여 특정 조건에 대한 알림을 설정할 수 있습니다.

  1. Grafana에서 알림 규칙 생성
  • 예 : 에러율이 5% 이상일 때 알림
  • Slack, Email 등의 알림 채널 설정
  1. 알림 테스트 및 미세 조정

15장 배포와의 연관성

 18장의 서버 사이드 로깅 및 모니터링은 15장에서 다룬 배포 과정과 밀접하게 연관됩니다. 로깅 및 모니터링 시스템은 배포 환경에 맞게 구성되어야 하며, 특히 클라우드 환경에서의 로그 관리와 모니터링 전략이 중요합니다. 또한, 무중단 배포나 롤백 상황에서의 로그 추적과 모니터링이 애플리케이션의 안정성을 유지하는 데 crucial합니다.

실습 : 종합적인 로깅 및 모니터링 시스템 구축

 Next.js App Router 애플리케이션에 종합적인 로깅 및 모니터링 시스템을 구축하고, 특정 시나리오에 대한 알림을 설정해보세요.

  1. Winston을 사용한 로깅 시스템 구현 :
// lib/logger.js
import winston from 'winston';
 
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  ),
  defaultMeta: { service: 'next-app' },
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' }),
  ],
});
 
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple(),
  }));
}
 
export default logger;
  1. Prometheus 메트릭 설정 :
// lib/metrics.js
import prometheus from 'prom-client';
 
const collectDefaultMetrics = prometheus.collectDefaultMetrics;
collectDefaultMetrics({ timeout: 5000 });
 
const httpRequestDurationMicroseconds = new prometheus.Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'code'],
  buckets: [0.1, 0.3, 0.5, 0.7, 1, 3, 5, 7, 10]
});
 
export { httpRequestDurationMicroseconds };
  1. 미들웨어를 사용한 로깅 및 메트릭 수집 :
// middleware.js
import { NextResponse } from 'next/server';
import logger from './lib/logger';
import { httpRequestDurationMicroseconds } from './lib/metrics';
 
export function middleware(request) {
  const start = Date.now();
 
  const response = NextResponse.next();
 
  response.on('finish', () => {
    const duration = Date.now() - start;
    const { method, url } = request;
    const { statusCode } = response;
 
    logger.info(`${method} ${url} ${statusCode} - ${duration}ms`);
 
    httpRequestDurationMicroseconds
      .labels(method, url, statusCode.toString())
      .observe(duration / 1000);
  });
 
  return response;
}
  1. 메트릭 엔드포인트 생성 :
// app/api/metrics/route.js
import { NextResponse } from 'next/server';
import prometheus from 'prom-client';
 
export async function GET() {
  const metrics = await prometheus.register.metrics();
  return new NextResponse(metrics, {
    headers: {
      'Content-Type': prometheus.register.contentType
    }
  });
}
  1. Grafana 대시보드 설정 :
  • Prometheus 데이터 소스 연결
  • 요청 속도, 에러율, 리소스 사용량 등을 시각화하는 대시보드 생성
  1. 알림 규칙 설정 :
  • 에러율이 5% 이상일 때 Slack 알림 설정
  • 평균 응답 시간이 1초 이상일 때 이메일 알림 설정

 이 실습을 통해 Next.js App Router 애플리케이션에 종합적인 로깅 및 모니터링 시스템을 구축하고, 실시간으로 애플리케이션의 상태를 모니터링하며 문제 상황에 대해 즉각적으로 알림을 받을 수 있는 환경을 구성할 수 있습니다.

 Next.js App Router 애플리케이션의 서버 사이드 로깅 및 모니터링은 애플리케이션의 안정성, 성능, 그리고 사용자 경험을 유지하는 데 crucial합니다. 구조화된 로깅, 중앙 집중식 로그 수집, 실시간 모니터링, 그리고 알림 시스템을 통해 개발 팀은 애플리케이션의 상태를 지속적으로 파악하고 문제 상황에 신속하게 대응할 수 있습니다. 이러한 시스템을 효과적으로 구축하고 활용함으로써, 더욱 안정적이고 신뢰할 수 있는 Next.js 애플리케이션을 운영할 수 있습니다.