에러 추적 및 프로덕션 모니터링
실사용자 환경에서 발생하는 이슈를 감지하고, 추적하며, 해결하는 전체 워크플로를 구축합니다.
프로덕션 모니터링이 필요한 이유
시스템 내부 상태를 외부에서 파악할 수 있는 능력, 즉 가시성(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)
가장 널리 사용되는 에러 트래킹 플랫폼으로 프로덕션 에러를 실시간으로 수집하고 분석합니다.
핵심 기능
에러 자동 그룹핑
유사 에러를 자동으로 묶어 중복 알림을 줄입니다.
소스맵 지원
난독화된 코드를 원본으로 복원하여 디버깅합니다.
릴리스 추적
어떤 배포 버전에서 에러가 발생했는지 추적합니다.
사용자 영향도 분석
에러로 인해 영향받는 사용자 수를 파악합니다.
에러 추적 시뮬레이터
설치 및 설정
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 통합
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,
}),
],
});주의사항
세션 리플레이
사용자의 세션을 비디오처럼 재생하여 문제 상황을 정확히 이해할 수 있게 해주는 기능입니다.
세션 리플레이란?
기존 에러 리포트
"TypeError: Cannot read property 'name' of undefined" → 어떤 상황에서? 어떤 동작 후?
세션 리플레이
사용자가 상품 목록 → 상세 → 장바구니 → 에러 발생 → 정확한 재현 경로 파악
세션 리플레이 데모
페이지 로드
/products
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 설정
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 통합
import LogRocket from "logrocket";
import * as Sentry from "@sentry/react";
LogRocket.getSessionURL((sessionURL) => {
Sentry.configureScope((scope) => {
scope.setExtra("sessionURL", sessionURL);
});
});입력 필드
maskAllInputs: true로 모든 입력 마스킹
네트워크 요청
Authorization 헤더 등 인증 정보 제거
텍스트 콘텐츠
이메일, 전화번호 등 정규식으로 마스킹
미디어
blockAllMedia로 이미지/비디오 차단 가능
성능 영향
실사용자 모니터링 (RUM)
실제 사용자의 브라우저에서 성능 데이터를 수집하여 분석하는 기법입니다.
합성 모니터링 vs RUM
| Synthetic | RUM | |
|---|---|---|
| 환경 | 통제된 환경 | 실제 사용자 환경 |
| 범위 | 주기적 테스트 | 모든 페이지뷰 |
| 용도 | 문제 탐지 | 실제 경험 측정 |
Core Web Vitals
LCP (Largest Contentful Paint)
메인 콘텐츠가 로딩되는 시간
INP (Interaction to Next Paint)
사용자 인터랙션 후 다음 페인트까지의 시간
CLS (Cumulative Layout Shift)
예상치 못한 레이아웃 이동 정도
FCP (First Contentful Paint)
첫 번째 콘텐츠가 렌더링되는 시간
TTFB (Time To First Byte)
서버 응답 첫 바이트까지의 시간
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,
});샘플링 전략
사용자 분석
이벤트 트래킹으로 사용자 행동을 이해하고, 데이터 기반 의사결정을 지원합니다.
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 |
이벤트 스트림 데모
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;
}
}프라이버시 정책
알림 및 대시보드
심각도에 따른 알림 체계를 구축하고, 핵심 지표를 모니터링하는 대시보드를 설계합니다.
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초 | 성능 채널 알림 |
알림 규칙 시뮬레이터
대시보드 구성
에러 메트릭
- •시간당 에러 수
- •에러 유형별 분포
- •영향받은 사용자 수
- •가장 빈번한 에러 TOP 10
성능 메트릭
- •Core Web Vitals (LCP, INP, CLS)
- •페이지별 로드 시간
- •API 응답 시간
- •JavaScript 에러율
사용자 메트릭
- •DAU/MAU
- •전환율 (퍼널 분석)
- •이탈률
- •세션 지속 시간
알림 피로도 관리
- ●심각도별 채널 분리 (critical → 긴급 채널, info → 일반 채널)
- ●중복 알림 억제 (같은 이슈 반복 시 요약 전송)
- ●근무 시간 외 알림은 critical만 전송
- ●주간 리뷰를 통한 알림 규칙 최적화
인시던트 대응
에러 처리 모범 사례
전역 에러 핸들러부터 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 계층화
// 페이지 레벨 에러 경계
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>
);
}에러 분류 체계
예시: 네트워크 일시 오류, 확장 프로그램 충돌
처리: 로깅만 수행
예시: 비핵심 API 실패, 이미지 로드 실패
처리: 대체 UI 표시, 비동기 알림
예시: 인증 실패, 결제 페이지 오류
처리: 즉시 알림, 에러 페이지 표시
예시: 메인 페이지 렌더링 실패, 데이터 손실
처리: 긴급 호출, 즉시 롤백 검토
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;
}에러 분류 흐름 시뮬레이터
에러 처리 체크리스트
개인정보 보호
모니터링 데이터 수집 시 개인정보보호법과 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
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);
}