Skip to Content
22주차 · 에러 추적 & 프로덕션 모니터링

에러 추적 및 프로덕션 모니터링

실사용자 환경에서 발생하는 이슈를 감지하고, 추적하며, 해결하는 전체 워크플로를 구축합니다.

프로덕션 모니터링이 필요한 이유

모니터링

시스템 내부 상태를 외부에서 파악할 수 있는 능력, 즉 가시성(Observability)이 안정적인 서비스 운영의 핵심입니다.

핵심 개념

가시성 (Observability)

시스템 내부 상태를 외부에서 파악할 수 있는 능력입니다.

MTTD (Mean Time To Detect)

문제 발견까지 걸리는 평균 시간입니다.

MTTR (Mean Time To Resolve)

문제 해결까지 걸리는 평균 시간입니다.

SLI / SLO / SLA

서비스 수준 지표, 목표, 계약으로 이루어진 서비스 품질 프레임워크입니다.

로컬 vs 프로덕션 환경

로컬프로덕션
디버깅console.log로 즉시 확인로그 수집 시스템 필요
에러 확인스택트레이스 즉시 확인사용자 신고 없으면 모름
네트워크DevTools 탭으로 확인다양한 환경 변수 존재
환경 통제모든 환경 통제 가능수천 가지 브라우저/기기

모니터링 없이 발생하는 문제

사일런트 에러

사용자가 떠나도 모름

성능 저하

전환율 하락, 원인 불명

특정 환경 버그

재현 불가, 해결 불가

메모리 누수

점진적 성능 저하

SLI / SLO / SLA 프레임워크

SLI (Service Level Indicator)

서비스 수준을 측정하는 지표

99.5% 요청이 200ms 이내 응답

SLO (Service Level Objective)

서비스 수준 목표

월간 가용성 99.9% 이상 유지

SLA (Service Level Agreement)

서비스 수준 계약

SLO 미달 시 크레딧 보상 약정

장애 대응 시뮬레이터

인터랙티브 데모
에러 발생
알림 발생
팀 대응
해결 완료

핵심 정리

프로덕션 모니터링은 '사후 대응'이 아닌 '사전 예방'을 위한 것입니다. 에러가 발생하기 전에 경고 신호를 파악하고, 사용자가 불편을 느끼기 전에 문제를 해결하는 것이 목표입니다.

에러 추적 (Sentry)

Sentry

가장 널리 사용되는 에러 트래킹 플랫폼으로 프로덕션 에러를 실시간으로 수집하고 분석합니다.

핵심 기능

에러 자동 그룹핑

유사 에러를 자동으로 묶어 중복 알림을 줄입니다.

소스맵 지원

난독화된 코드를 원본으로 복원하여 디버깅합니다.

릴리스 추적

어떤 배포 버전에서 에러가 발생했는지 추적합니다.

사용자 영향도 분석

에러로 인해 영향받는 사용자 수를 파악합니다.

에러 추적 시뮬레이터

인터랙티브 데모
에러 대시보드
에러를 발생시키면 여기에 그룹화되어 표시됩니다

설치 및 설정

설치 및 설정
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "https://xxxxx@xxx.ingest.sentry.io/xxxxx",
  environment: import.meta.env.MODE,
  release: import.meta.env.VITE_APP_VERSION,
  integrations: [
    Sentry.browserTracingIntegration(),
    Sentry.replayIntegration(),
  ],
  tracesSampleRate: 0.1,
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
  beforeSend(event) {
    if (event.user) {
      delete event.user.email;
    }
    return event;
  },
});

수동 에러 캡처

수동 에러 캡처
import * as Sentry from "@sentry/react";

try {
  await riskyOperation();
} catch (error) {
  Sentry.captureException(error, {
    tags: {
      feature: "checkout",
      severity: "critical",
    },
    extra: {
      userId: currentUser.id,
      cartItems: cart.items.length,
    },
  });
}

// 스코프 설정
Sentry.withScope((scope) => {
  scope.setTag("transaction", "checkout");
  scope.setUser({ id: user.id });
  scope.setContext("order", { orderId, amount });
  Sentry.captureException(error);
});

React 통합

React 통합
import * as Sentry from "@sentry/react";

function App() {
  return (
    <Sentry.ErrorBoundary
      fallback={({ error, resetError }) => (
        <div>
          <h1>오류가 발생했습니다</h1>
          <p>{error.message}</p>
          <button onClick={resetError}>다시 시도</button>
        </div>
      )}
      onError={(error, componentStack) => {
        console.error("Error caught:", error);
      }}
    >
      <Router>
        <Routes />
      </Router>
    </Sentry.ErrorBoundary>
  );
}

소스맵 업로드

소스맵 업로드
// vite.config.ts
import { sentryVitePlugin } from "@sentry/vite-plugin";

export default defineConfig({
  build: {
    sourcemap: true,
  },
  plugins: [
    sentryVitePlugin({
      org: "my-org",
      project: "my-project",
      authToken: process.env.SENTRY_AUTH_TOKEN,
    }),
  ],
});

주의사항

Sentry에 전송되는 데이터에 민감한 개인정보(PII)가 포함되지 않도록 beforeSend 콜백에서 반드시 필터링하세요. 이메일, 비밀번호, 신용카드 정보 등이 로깅되면 보안 문제가 발생할 수 있습니다.

세션 리플레이

Session Replay

사용자의 세션을 비디오처럼 재생하여 문제 상황을 정확히 이해할 수 있게 해주는 기능입니다.

세션 리플레이란?

기존 에러 리포트

"TypeError: Cannot read property 'name' of undefined" → 어떤 상황에서? 어떤 동작 후?

세션 리플레이

사용자가 상품 목록 → 상세 → 장바구니 → 에러 발생 → 정확한 재현 경로 파악

세션 리플레이 데모

인터랙티브 데모
0.0s / 16s

페이지 로드

/products

0.0s
0.0s페이지 로드/products
2.0s스크롤 다운scrollY: 450px
4.0s상품 클릭Product #42 card
5.0s페이지 이동/products/42
7.0s장바구니 담기Button: Add to Cart
9.0s페이지 이동/cart
11.0s폼 입력Email field
13.0s결제Button: Pay Now
14.0s에러!TypeError: Cannot read property 'id' of null

Sentry Replay 설정

Sentry Replay 설정
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "...",
  integrations: [
    Sentry.replayIntegration({
      maskAllText: false,
      maskAllInputs: true,
      blockAllMedia: false,
      networkDetailAllowUrls: ["/api"],
      networkCaptureBodies: true,
    }),
  ],
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

LogRocket 설정

LogRocket 설정
import LogRocket from "logrocket";
import setupLogRocketReact from "logrocket-react";

LogRocket.init("org-id/app-id", {
  release: import.meta.env.VITE_APP_VERSION,
  network: {
    requestSanitizer: (request) => {
      if (request.headers.Authorization) {
        request.headers.Authorization = "[REDACTED]";
      }
      return request;
    },
  },
  dom: {
    inputSanitizer: true,
    textSanitizer: (text) => {
      return text.replace(/\S+@\S+/g, "[EMAIL]");
    },
  },
});

setupLogRocketReact(LogRocket);

Sentry + LogRocket 통합

Sentry + LogRocket 통합
import LogRocket from "logrocket";
import * as Sentry from "@sentry/react";

LogRocket.getSessionURL((sessionURL) => {
  Sentry.configureScope((scope) => {
    scope.setExtra("sessionURL", sessionURL);
  });
});

입력 필드

maskAllInputs: true로 모든 입력 마스킹

네트워크 요청

Authorization 헤더 등 인증 정보 제거

텍스트 콘텐츠

이메일, 전화번호 등 정규식으로 마스킹

미디어

blockAllMedia로 이미지/비디오 차단 가능

성능 영향

세션 리플레이는 DOM 변경을 지속적으로 캡처하므로 성능에 영향을 줄 수 있습니다. 프로덕션에서는 replaysSessionSampleRate를 낮게 설정하고, 에러 발생 시에만 100% 캡처하는 전략을 권장합니다.

실사용자 모니터링 (RUM)

RUM

실제 사용자의 브라우저에서 성능 데이터를 수집하여 분석하는 기법입니다.

합성 모니터링 vs RUM

SyntheticRUM
환경통제된 환경실제 사용자 환경
범위주기적 테스트모든 페이지뷰
용도문제 탐지실제 경험 측정

Core Web Vitals

LCP (Largest Contentful Paint)

메인 콘텐츠가 로딩되는 시간

2.5초 이하

INP (Interaction to Next Paint)

사용자 인터랙션 후 다음 페인트까지의 시간

200ms 이하

CLS (Cumulative Layout Shift)

예상치 못한 레이아웃 이동 정도

0.1 이하

FCP (First Contentful Paint)

첫 번째 콘텐츠가 렌더링되는 시간

1.8초 이하

TTFB (Time To First Byte)

서버 응답 첫 바이트까지의 시간

0.8초 이하

Web Vitals 시뮬레이터

인터랙티브 데모
1.8s
LCP좋음
120ms
INP좋음
0.05
CLS좋음
LCP 임계값
≤ 2.5s≤ 4s> 4s
INP 임계값
≤ 200ms≤ 500ms> 500ms
CLS 임계값
≤ 0.1≤ 0.25> 0.25

web-vitals 라이브러리

web-vitals 라이브러리
import { onCLS, onINP, onLCP, onFCP, onTTFB } from "web-vitals";

function sendToAnalytics(metric) {
  // Sentry로 전송
  Sentry.captureMessage("Web Vital", {
    level: "info",
    tags: {
      metric_name: metric.name,
      metric_rating: metric.rating,
    },
    extra: {
      value: metric.value,
      delta: metric.delta,
      id: metric.id,
    },
  });
}

export function reportWebVitals() {
  onCLS(sendToAnalytics);
  onINP(sendToAnalytics);
  onLCP(sendToAnalytics);
  onFCP(sendToAnalytics);
  onTTFB(sendToAnalytics);
}

커스텀 성능 측정

커스텀 성능 측정
function useRenderTracking(componentName: string) {
  const startTime = useRef(performance.now());

  useEffect(() => {
    const duration = performance.now() - startTime.current;
    Sentry.addBreadcrumb({
      category: "render",
      message: `${componentName} rendered`,
      data: { duration },
      level: "info",
    });

    if (duration > 100) {
      Sentry.captureMessage(
        `Slow render: ${componentName}`,
        { level: "warning", extra: { duration } }
      );
    }
  }, [componentName]);
}

분석 서비스로 전송

분석 서비스로 전송
// Google Analytics로 전송
gtag("event", metric.name, {
  event_category: "Web Vitals",
  value: Math.round(
    metric.name === "CLS"
      ? metric.value * 1000
      : metric.value
  ),
  event_label: metric.id,
  non_interaction: true,
});

샘플링 전략

프로덕션 환경에서 모든 사용자의 성능 데이터를 수집하면 비용이 급증합니다. tracesSampleRate를 0.1(10%)로 설정하여 적절한 샘플링 비율을 유지하세요. 통계적으로 유의미한 데이터만 수집해도 충분합니다.

사용자 분석

Analytics

이벤트 트래킹으로 사용자 행동을 이해하고, 데이터 기반 의사결정을 지원합니다.

Google Analytics 4 설정

Google Analytics 4 설정
export function initGA(measurementId: string) {
  const script = document.createElement("script");
  script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
  script.async = true;
  document.head.appendChild(script);

  window.dataLayer = window.dataLayer || [];
  window.gtag = function () {
    window.dataLayer.push(arguments);
  };

  window.gtag("js", new Date());
  window.gtag("config", measurementId, {
    send_page_view: false, // SPA에서는 수동으로 처리
  });
}

이벤트 트래킹 설계

이벤트설명파라미터
product_view상품 조회productId, category
add_to_cart장바구니 추가productId, quantity, price
checkout_start결제 시작cartValue, itemCount
checkout_complete결제 완료orderId, value
search검색query, resultCount
error에러 발생errorType, message

이벤트 스트림 데모

인터랙티브 데모
mystore.com
상품 이미지
이벤트 스트림
웹사이트와 상호작용하면 이벤트가 표시됩니다

React Router 통합

React Router 통합
import { useLocation } from "react-router-dom";
import { useEffect } from "react";
import { trackPageView } from "./utils/analytics";

function App() {
  const location = useLocation();

  useEffect(() => {
    trackPageView(
      location.pathname + location.search
    );
  }, [location]);

  return <Routes />;
}

커스텀 이벤트 추적

커스텀 이벤트 추적
type AnalyticsEvent =
  | { type: "product_view"; productId: string }
  | { type: "add_to_cart"; productId: string;
      quantity: number; price: number }
  | { type: "checkout_complete"; orderId: string;
      value: number };

export function track(event: AnalyticsEvent) {
  switch (event.type) {
    case "product_view":
      window.gtag("event", "view_item", {
        items: [{ item_id: event.productId }],
      });
      break;
    case "add_to_cart":
      window.gtag("event", "add_to_cart", {
        currency: "KRW",
        value: event.price * event.quantity,
      });
      break;
  }
}

프라이버시 정책

분석 데이터 수집 시 개인정보보호법과 GDPR 규정을 반드시 준수하세요. SPA에서는 send_page_view를 비활성화하고 라우트 변경 시 수동으로 페이지뷰를 전송해야 정확한 데이터를 수집할 수 있습니다.

알림 및 대시보드

알림

심각도에 따른 알림 체계를 구축하고, 핵심 지표를 모니터링하는 대시보드를 설계합니다.

Slack 알림 설정

Slack 알림 설정
type AlertLevel = "info" | "warning" | "critical";

async function sendSlackAlert(alert: {
  level: AlertLevel;
  title: string;
  message: string;
  context?: Record<string, any>;
}) {
  const color = {
    info: "#36a64f",
    warning: "#ff9500",
    critical: "#ff0000",
  }[alert.level];

  await fetch(webhookUrl, {
    method: "POST",
    body: JSON.stringify({
      attachments: [{
        color,
        title: alert.title,
        text: alert.message,
        ts: Math.floor(Date.now() / 1000),
      }],
    }),
  });
}

알림 규칙 설정

알림 규칙 설정임계값조치
새로운 이슈 발생즉시Slack 채널 알림
동일 이슈 반복1시간 내 10회 이상Slack + 이메일 알림
에러율 급증5분간 에러율 5% 초과긴급 호출 (PagerDuty)
성능 저하LCP > 4초성능 채널 알림

알림 규칙 시뮬레이터

인터랙티브 데모
에러율0.5%
0%1%3%5%10%15%
알림 규칙
에러율이 기준치를 초과함
≥ 1%
에러율 상승 - 조사 필요
≥ 3%
에러율 위험 - 즉시 조치 필요
≥ 5%
서비스 성능 저하 - 온콜 호출
≥ 10%

대시보드 구성

에러 메트릭

  • •시간당 에러 수
  • •에러 유형별 분포
  • •영향받은 사용자 수
  • •가장 빈번한 에러 TOP 10

성능 메트릭

  • •Core Web Vitals (LCP, INP, CLS)
  • •페이지별 로드 시간
  • •API 응답 시간
  • •JavaScript 에러율

사용자 메트릭

  • •DAU/MAU
  • •전환율 (퍼널 분석)
  • •이탈률
  • •세션 지속 시간

알림 피로도 관리

  • ●심각도별 채널 분리 (critical → 긴급 채널, info → 일반 채널)
  • ●중복 알림 억제 (같은 이슈 반복 시 요약 전송)
  • ●근무 시간 외 알림은 critical만 전송
  • ●주간 리뷰를 통한 알림 규칙 최적화

인시던트 대응

알림 시스템의 핵심은 '행동 가능한 알림'만 보내는 것입니다. 모든 에러를 알림으로 보내면 알림 피로도가 높아져 정작 중요한 알림을 놓칠 수 있습니다. 심각도 분류와 에스컬레이션 정책을 사전에 수립하세요.

에러 처리 모범 사례

Best Practices

전역 에러 핸들러부터 Error Boundary 계층화, 에러 분류 체계까지 체계적인 에러 처리 전략을 세웁니다.

전역 에러 핸들러

전역 에러 핸들러
// 전역 에러 핸들러
window.onerror = (message, source, lineno, colno, error) => {
  Sentry.captureException(
    error || new Error(String(message)),
    { extra: { source, lineno, colno } }
  );
};

// Promise 거부 핸들러
window.onunhandledrejection = (event) => {
  Sentry.captureException(event.reason, {
    tags: { type: "unhandledrejection" },
  });
};

// 안전한 fetch 래퍼
export async function safeFetch<T>(
  url: string,
  options?: RequestInit
): Promise<T> {
  try {
    const response = await fetch(url, options);
    if (!response.ok) {
      const error = new Error(
        `HTTP ${response.status}: ${response.statusText}`
      );
      Sentry.captureException(error);
      throw error;
    }
    return response.json();
  } catch (error) {
    if (error instanceof TypeError) {
      Sentry.captureException(error, {
        tags: { errorType: "network" },
      });
    }
    throw error;
  }
}

Error Boundary 계층화

Error Boundary 계층화
// 페이지 레벨 에러 경계
function PageErrorBoundary({ children }) {
  return (
    <Sentry.ErrorBoundary
      fallback={({ error, resetError }) => (
        <div className="error-page">
          <h1>페이지를 불러올 수 없습니다</h1>
          <button onClick={resetError}>다시 시도</button>
        </div>
      )}
      beforeCapture={(scope) => {
        scope.setTag("errorBoundary", "page");
      }}
    >
      {children}
    </Sentry.ErrorBoundary>
  );
}

// 컴포넌트 레벨 에러 경계
function ComponentErrorBoundary({ children, fallback }) {
  return (
    <Sentry.ErrorBoundary
      fallback={fallback || <div>콘텐츠를 불러올 수 없습니다.</div>}
      beforeCapture={(scope) => {
        scope.setTag("errorBoundary", "component");
      }}
    >
      {children}
    </Sentry.ErrorBoundary>
  );
}
사용 예시
// 사용 예시
function App() {
  return (
    <PageErrorBoundary>
      <Header />
      <main>
        <ComponentErrorBoundary>
          <ProductList />
        </ComponentErrorBoundary>
        <ComponentErrorBoundary>
          <Recommendations />
        </ComponentErrorBoundary>
      </main>
      <Footer />
    </PageErrorBoundary>
  );
}

에러 분류 체계

LOW무시해도 되는 에러

예시: 네트워크 일시 오류, 확장 프로그램 충돌

처리: 로깅만 수행

MEDIUM기능 저하

예시: 비핵심 API 실패, 이미지 로드 실패

처리: 대체 UI 표시, 비동기 알림

HIGH주요 기능 장애

예시: 인증 실패, 결제 페이지 오류

처리: 즉시 알림, 에러 페이지 표시

CRITICAL서비스 불가

예시: 메인 페이지 렌더링 실패, 데이터 손실

처리: 긴급 호출, 즉시 롤백 검토

에러 분류 체계
enum ErrorSeverity {
  LOW = "low",
  MEDIUM = "medium",
  HIGH = "high",
  CRITICAL = "critical",
}

function classifyError(error: Error): ErrorSeverity {
  if (error.name === "TypeError"
    && error.message.includes("fetch")) {
    return ErrorSeverity.LOW;
  }
  if (error.message.includes("payment")) {
    return ErrorSeverity.CRITICAL;
  }
  if (error.message.includes("auth")) {
    return ErrorSeverity.HIGH;
  }
  return ErrorSeverity.MEDIUM;
}

에러 분류 흐름 시뮬레이터

인터랙티브 데모
에러 수신
분석
심각도
조치

에러 처리 체크리스트

전역 핸들러 설정, Error Boundary 계층화, 에러 심각도 분류, 네트워크 에러 재시도 로직, 사용자 친화적 에러 메시지, Sentry 컨텍스트 추가를 반드시 점검하세요.

개인정보 보호

Privacy

모니터링 데이터 수집 시 개인정보보호법과 GDPR 규정을 준수하며, 사용자 동의 기반 초기화를 구현합니다.

민감 데이터 마스킹

민감 데이터 마스킹
Sentry.init({
  beforeSend(event) {
    // 이메일 마스킹
    if (event.user?.email) {
      event.user.email = maskEmail(event.user.email);
    }
    // 요청 데이터에서 민감 정보 제거
    if (event.request?.data) {
      const data = JSON.parse(event.request.data);
      delete data.password;
      delete data.creditCard;
      delete data.ssn;
      event.request.data = JSON.stringify(data);
    }
    return event;
  },
  beforeBreadcrumb(breadcrumb) {
    if (breadcrumb.category === "console") {
      if (breadcrumb.message?.includes("token")) {
        return null;
      }
    }
    return breadcrumb;
  },
  denyUrls: [
    /\/api\/auth/,
    /\/api\/payment/,
  ],
});

function maskEmail(email: string): string {
  const [local, domain] = email.split("@");
  return `${local[0]}***@${domain}`;
}

데이터 마스킹 데모

인터랙티브 데모

// user data object

이름
Kim Manjoong
이메일
kim.manjoong@example.com
전화번호
+82-10-1234-5678
주민등록번호
901215-1234567
IP 주소
192.168.1.42
신용카드
4242-4242-4242-4242
경고: 개인정보(PII)가 원본 그대로 노출되어 있습니다

GDPR 준수

명시적 동의

쿠키 동의 배너를 통해 모니터링 도구별 동의를 수집합니다.

데이터 최소화

목적에 필요한 최소한의 데이터만 수집하고 불필요한 PII를 제거합니다.

데이터 접근권

사용자가 자신의 수집 데이터를 조회할 수 있는 API를 제공합니다.

삭제 요청 처리

GDPR 삭제 요청 시 Sentry, 분석 서비스에서 사용자 데이터를 삭제합니다.

동의 기반 초기화

동의 기반 초기화
interface UserConsent {
  analytics: boolean;
  errorTracking: boolean;
  sessionReplay: boolean;
}

function initializeMonitoring(consent: UserConsent) {
  if (consent.analytics) {
    initGA(GA_ID);
  }

  if (consent.errorTracking) {
    Sentry.init({
      dsn: SENTRY_DSN,
      integrations: consent.sessionReplay
        ? [Sentry.replayIntegration()]
        : [],
    });
  }
}

데이터 삭제 요청 처리

데이터 삭제 요청 처리
async function handleDataDeletionRequest(
  userId: string
) {
  // Sentry 사용자 데이터 삭제
  await fetch(
    `https://sentry.io/api/0/projects/.../users/${userId}/`,
    {
      method: "DELETE",
      headers: {
        Authorization: `Bearer ${SENTRY_API_TOKEN}`,
      },
    }
  );

  // 분석 데이터 삭제
  await deleteUserAnalyticsData(userId);
}

법적 고려사항

개인정보 보호 규정은 지역마다 다릅니다(한국 개인정보보호법, EU GDPR, 미국 CCPA 등). 서비스 대상 지역의 법률을 확인하고, 모니터링 도구 도입 시 반드시 법무팀과 협의하세요. 기술적 구현뿐 아니라 조직적 프로세스(데이터 보호 책임자 지정, 영향 평가 등)도 필요합니다.
마지막 업데이트