stack-analysis
CHAPTER 58 / 90
읽기 약 2분
FUNCTION
모니터링: Sentry + Logflare
핵심 개념
에러 추적·로그·성능·세션 리플레이 — 프로덕션 가시성.
본문
Sentry — 에러 추적
pnpm add @sentry/nextjs
pnpm dlx @sentry/wizard@latest -i nextjs// sentry.client.config.ts
import * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
environment: process.env.VERCEL_ENV || 'development',
release: process.env.VERCEL_GIT_COMMIT_SHA,
tracesSampleRate: 0.1, // 10% 트랜잭션 추적
replaysSessionSampleRate: 0.0, // 일반 세션 0%
replaysOnErrorSampleRate: 1.0, // 에러 시 100% 리플레이
integrations: [
Sentry.replayIntegration({
maskAllText: false,
blockAllMedia: false,
}),
],
// 무시할 에러
ignoreErrors: [
'ResizeObserver loop limit exceeded',
/^NetworkError/,
],
beforeSend(event, hint) {
// 사용자 정보 익명화
if (event.user) {
event.user.email = undefined;
}
return event;
},
});
// sentry.server.config.ts (server)
Sentry.init({
dsn: process.env.SENTRY_DSN,
tracesSampleRate: 0.1,
profilesSampleRate: 1.0, // 프로파일링
});컨텍스트 추가
import * as Sentry from '@sentry/nextjs';
// 사용자 정보
Sentry.setUser({ id: user.id, role: user.role });
// 태그
Sentry.setTag('feature', 'checkout');
// 에러에 추가 데이터
try {
await processPayment(orderId);
} catch (err) {
Sentry.captureException(err, {
tags: { orderId },
extra: { amount, currency },
});
throw err;
}
// 수동 이벤트
Sentry.captureMessage('Suspicious activity', 'warning');Source Maps (디버깅)
// next.config.js
const { withSentryConfig } = require('@sentry/nextjs');
module.exports = withSentryConfig(
nextConfig,
{
silent: true,
org: 'my-org',
project: 'web',
},
{
widenClientFileUpload: true,
transpileClientSDK: false,
tunnelRoute: '/monitoring', // ad blocker 우회
hideSourceMaps: true,
disableLogger: true,
}
);
// 빌드 시 source map → Sentry 업로드
// → 프로덕션 minified 코드를 원본 코드로 표시Logflare (구조화 로그)
// pino + Logflare
import pino from 'pino';
const logger = pino({
transport: process.env.NODE_ENV === 'production' ? {
target: 'pino-logflare',
options: {
apiKey: process.env.LOGFLARE_API_KEY!,
sourceToken: process.env.LOGFLARE_SOURCE_TOKEN!,
},
} : { target: 'pino-pretty' },
});
// 사용
logger.info({ userId, orderId, amount }, 'Order placed');
logger.warn({ ip, userAgent }, 'Suspicious request');
logger.error({ err: error, requestId }, 'Payment failed');
// → Logflare에서 SQL로 검색
// SELECT * FROM logs WHERE userId = '...' AND level = 'error'메트릭 — Vercel Analytics + Speed Insights
// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/next';
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
<SpeedInsights />
</body>
</html>
);
}
// 자동 수집:
// - Page views, unique visitors
// - Web Vitals (LCP, FID, CLS, INP)
// - 디바이스·국가별 분포Uptime + Status Page
BetterStack ($25/mo):
- 30초 간격 체크
- 5+ 글로벌 위치
- Status page (status.example.com)
- Slack/Discord/SMS 알림
무료 옵션:
- UptimeRobot (5분 간격)
- Cronitor (cron job 모니터링)APM (Application Performance Monitoring)
// 자동 트랜잭션 추적
import * as Sentry from '@sentry/nextjs';
router.get('/orders', async (req, res) => {
const transaction = Sentry.getCurrentScope().getTransaction();
// DB 쿼리 추적
const dbSpan = transaction?.startChild({ op: 'db.query' });
const orders = await db.order.findMany();
dbSpan?.finish();
// 외부 API 추적
const apiSpan = transaction?.startChild({ op: 'http.client' });
const inventory = await fetch('https://inventory-api/').then(r => r.json());
apiSpan?.finish();
res.json({ orders, inventory });
});
// → Sentry 대시보드에서 latency breakdown
// DB 200ms, API 500ms, render 100ms알림 룰 설계
[Critical (즉시 알림)]
- 5분 이상 다운
- 5분 내 에러율 5%+
- 결제 실패율 1%+
[Warning (10분 후 알림)]
- 응답 시간 P95 > 2s
- 메모리 90%+
- 새로운 에러 타입
[Info (다이제스트)]
- 일일 에러 요약
- 주간 성능 변화다음 챕터
CH.59 "비용 최적화: 무료→유료 전환 시점".
AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude
무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6
내 코드의 모니터링 부분을 분석해서 실전 분석 + 개선 우선순위를 알려줘.
ChatGPT
무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro
모니터링 관련 인기 라이브러리/패턴 5개를 비교 분석해서 패턴 추출를 알려줘.
Gemini
무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro
내 프로젝트 전체에서 모니터링 최적화 가능 위치를 보고해줘.
Grok
무료: Grok 4.1 / SuperGrok $30/mo
2026년 한국 백엔드 시장의 모니터링 트렌드를 솔직히 알려줘.
⭐ 이것만 기억하세요
모니터링: Sentry + Logflare는 이 3가지만 확실히 잡으세요
1.Sentry = 에러 추적 표준 — 무료 5K events/mo로 시작
2.Replay (에러 시 100%)로 재현 — 디버깅 시간 90% 단축
3.구조화 로그(pino) + Logflare/Datadog = SQL로 검색 가능
공유하기
진행도 58 / 90