[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,129 +2,354 @@
|
||||
id: wiki-2026-0508-debugging-methods
|
||||
title: Debugging Methods
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [debugging, frontend debugging, observability, Sentry, LogRocket, time-travel debug, session replay]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [debugging, observability, sentry, logrocket, devtools, error-boundary, time-travel, profiling]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: JS / Python / Go
|
||||
framework: Sentry / Datadog / Chrome DevTools / Redux DevTools
|
||||
---
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
현대 프론트엔드 디버깅은 런타임 에러 포착, 성능 병목 진단, 상태 불일치 해결을 아우르는 체계적인 분석 과정이다. 브라우저 개발자 도구(Chrome DevTools)를 통한 로컬 분석부터 Sentry, Datadog과 같은 관측성(Observability) 플랫폼을 활용한 프로덕션 모니터링까지 통합적인 접근을 통해 시스템의 신뢰성을 확보한다.
|
||||
# Debugging Methods
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
1. **프로덕션 관측성 (Observability Platforms)**
|
||||
- Sentry, LogRocket 등을 통한 실시간 에러 그룹화 및 사용자 여정(Breadcrumbs) 추적.
|
||||
- **세션 리플레이(Session Replay)**: 에러 발생 전의 사용자 조작과 상태 변화를 시각적으로 재현하여 재현 불가능한 버그 차단.
|
||||
- **분산 트레이싱**: 프론트엔드 에러와 백엔드 트레이스 ID를 연결하여 엔드-투-엔드 문제 진단.
|
||||
2. **메모리 누수 진단 (Memory Profiling)**
|
||||
- Chrome DevTools의 **Heap Snapshots**을 비교하여 분리된 DOM 노드(Detached DOM nodes)와 가비지 컬렉션(GC)되지 않는 객체 식별.
|
||||
- **Allocation Timelines**: 메모리 할당 시점과 리테이너 경로(Retainer paths)를 분석하여 객체 보존 원인 파악.
|
||||
3. **상태 및 렌더링 디버깅**
|
||||
- **Time-travel Debugging**: Redux DevTools 등을 통해 상태 변화를 기록하고 특정 시점으로 액션을 재생하여 비동기 버그 추적.
|
||||
- **Error Boundaries**: React의 렌더링 에러를 선언적으로 포착하여 전체 앱 크래시를 방지하고 에러 스택 정보를 확보.
|
||||
## 매 한 줄
|
||||
> **"매 hypothesis-driven 의 systematic"**. 매 reproduce → 매 narrow → 매 hypothesize → 매 test → 매 fix → 매 prevent. 매 modern: 매 observability (Sentry, Datadog) + 매 session replay + 매 distributed trace + 매 LLM-aided.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **로깅 오버헤드**: 과도한 로깅 및 관측성 도구 도입은 번들 사이즈 증가와 런타임 성능 저하를 유발할 수 있으므로 샘플링 전략이 필요하다.
|
||||
- **데이터 프라이버시**: 세션 리플레이 및 클라우드 로깅 시 사용자 민감 정보(비밀번호, PII)가 노출되지 않도록 엄격한 마스킹 처리가 선행되어야 한다.
|
||||
- **디버깅 도구의 제약**: React Context 등 특정 상태 관리 모델은 전용 디버깅 툴의 부재로 인해 문제 추적이 상대적으로 어렵다.
|
||||
## 매 핵심 process
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
### Related Concepts (Auto-Linked)
|
||||
* [[Boundaries]]
|
||||
* [[Chrome]]
|
||||
* [[Chrome_DevTools]]
|
||||
* [[Core_Web_Vitals]]
|
||||
* [[Error Boundaries]]
|
||||
* [[Heap Snapshot]]
|
||||
* [[Lighthouse]]
|
||||
* [[Observability]]
|
||||
* [[React]]
|
||||
* [[React Context]]
|
||||
* [[Redux]]
|
||||
* [[Research]]
|
||||
* [[SAST]]
|
||||
* [[Snapshots]]
|
||||
* [[Static_Application_Security_Testing]]
|
||||
* [[Testing]]
|
||||
* [[WebGL]]
|
||||
* [[memory]]
|
||||
### Scientific debugging
|
||||
1. **Reproduce**: 매 minimum reproducer.
|
||||
2. **Observe**: 매 relevant signal.
|
||||
3. **Hypothesize**: 매 specific cause.
|
||||
4. **Test**: 매 verify hypothesis.
|
||||
5. **Fix**: 매 root cause.
|
||||
6. **Prevent**: 매 test + 매 doc + 매 monitor.
|
||||
|
||||
### Related Concepts
|
||||
- **Heap Snapshots**: 자바스크립트 메모리 구조의 정적 분석 도구 (관계: 메모리 진단 핵심)
|
||||
- **Error Boundaries**: 런타임 에러 전파를 차단하는 선언적 격리 장치 (관계: 안정성 확보)
|
||||
- **Time-Travel Debugging**: 상태 불일치 원인을 규명하는 시계열 분석 기법 (관계: 비동기 로직 검증)
|
||||
### 매 method
|
||||
|
||||
### Deeper Research Questions
|
||||
1. OpenTelemetry를 활용하여 프론트엔드와 마이크로서비스 백엔드 간의 트레이스 컨텍스트를 어떻게 안전하게 전파하는가?
|
||||
2. Heap Snapshot 분석 시 'Shallow Size'와 'Retained Size'의 차이가 의미하는 가비지 컬렉션의 실제 작동 원리는?
|
||||
3. 세션 리플레이 도구가 캔버스(Canvas)나 WebGL 기반 렌더링의 상호작용을 어떻게 기록하고 재현하는가?
|
||||
4. 프로덕션 환경에서 소스 맵(Source Map) 노출 없이 에러 스택을 정확히 복구하는 보안 가이드라인은?
|
||||
5. 메모리 리테이너 경로 분석을 통해 발견된 '클로저(Closure)에 의한 메모리 누수'를 해결하는 코드 패턴은?
|
||||
#### Print / Log debugging
|
||||
- 매 simplest.
|
||||
- 매 strategic placement.
|
||||
|
||||
### Practical Application Contexts
|
||||
- **이슈 재현성 확보**: 고객사에서 보고된 불분명한 오류를 LogRocket 리플레이로 확인하여 재현 단계 생략.
|
||||
- **성능 튜닝**: 장시간 실행되는 대시보드 앱의 메모리 누수를 Allocation Timeline으로 추적하여 수정.
|
||||
#### Debugger (breakpoint)
|
||||
- 매 step-through.
|
||||
- 매 inspect state.
|
||||
- 매 conditional breakpoint.
|
||||
|
||||
### Adjacent Topics
|
||||
- **Performance Profiling (Lighthouse / Core Web Vitals)**
|
||||
- **Static Application Security Testing (SAST)**
|
||||
- **Unit & Integration Testing Strategies**
|
||||
#### Logging + observability
|
||||
- 매 structured log.
|
||||
- 매 distributed trace.
|
||||
- 매 metric.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
#### Time-travel
|
||||
- 매 Redux DevTools, Reduxify.
|
||||
- 매 action replay.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
#### Differential
|
||||
- 매 git bisect.
|
||||
- 매 binary search of commits.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
#### Rubber duck
|
||||
- 매 explain to inanimate.
|
||||
- 매 self-clarification.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
#### Profiling
|
||||
- 매 CPU / memory / GPU.
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### 매 modern stack
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
#### Frontend
|
||||
- **Sentry**: error tracking + session replay.
|
||||
- **LogRocket**: session replay focus.
|
||||
- **Datadog RUM**.
|
||||
- **PostHog**.
|
||||
- **Chrome DevTools** (Performance + Memory).
|
||||
- **React DevTools**.
|
||||
- **Redux DevTools**.
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
#### Backend
|
||||
- **Sentry**: error tracking.
|
||||
- **Datadog APM** / **New Relic**.
|
||||
- **OpenTelemetry**: standard.
|
||||
- **Honeycomb**: 매 observability 의 best.
|
||||
- **Jaeger / Zipkin**: tracing.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
#### Logs / metrics
|
||||
- **Grafana + Loki + Prometheus**.
|
||||
- **ELK / OpenSearch**.
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### LLM-aided debugging
|
||||
- **Cursor / Copilot**: 매 inline suggestion.
|
||||
- **Cody / Continue**: 매 codebase-aware.
|
||||
- **Sentry AI**: 매 root cause suggest.
|
||||
- **Stack trace → 매 LLM 의 fix proposal**.
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
### 매 prevention
|
||||
- **Type check** (TypeScript).
|
||||
- **Linter** (ESLint).
|
||||
- **Test** (unit / integration / e2e).
|
||||
- **Property-based test**.
|
||||
- **Sanitizer** (UBSan, ASan, TSan).
|
||||
- **Fuzz test**.
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
## 💻 패턴
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Sentry (frontend)
|
||||
```ts
|
||||
import * as Sentry from '@sentry/react';
|
||||
|
||||
Sentry.init({
|
||||
dsn: process.env.SENTRY_DSN,
|
||||
integrations: [
|
||||
Sentry.browserTracingIntegration(),
|
||||
Sentry.replayIntegration({
|
||||
maskAllText: true, // 매 PII protection
|
||||
blockAllMedia: true,
|
||||
}),
|
||||
],
|
||||
tracesSampleRate: 0.1, // 매 10%
|
||||
replaysSessionSampleRate: 0.05,
|
||||
replaysOnErrorSampleRate: 1.0, // 매 100% on error
|
||||
release: process.env.RELEASE,
|
||||
environment: process.env.NODE_ENV,
|
||||
});
|
||||
|
||||
// 매 manual breadcrumb
|
||||
Sentry.addBreadcrumb({
|
||||
category: 'auth',
|
||||
message: 'User logged in',
|
||||
level: 'info',
|
||||
});
|
||||
|
||||
// 매 manual capture
|
||||
try {
|
||||
riskyOperation();
|
||||
} catch (e) {
|
||||
Sentry.captureException(e, {
|
||||
tags: { feature: 'checkout' },
|
||||
extra: { orderId: '...' },
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Error Boundary (React)
|
||||
```tsx
|
||||
class ErrorBoundary extends React.Component {
|
||||
state = { hasError: false };
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error, info) {
|
||||
Sentry.captureException(error, { extra: info });
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) return <Fallback />;
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
<ErrorBoundary>
|
||||
<App />
|
||||
</ErrorBoundary>
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Distributed tracing (OpenTelemetry)
|
||||
```python
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
provider = TracerProvider()
|
||||
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
|
||||
trace.set_tracer_provider(provider)
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
tracer = trace.get_tracer(__name__)
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
@tracer.start_as_current_span('handle_request')
|
||||
def handle(req):
|
||||
span = trace.get_current_span()
|
||||
span.set_attribute('user.id', req.user.id)
|
||||
|
||||
with tracer.start_as_current_span('db_query') as db_span:
|
||||
db_span.set_attribute('db.statement', 'SELECT * FROM users WHERE id = ?')
|
||||
result = db.query(...)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
### git bisect (commit-level)
|
||||
```bash
|
||||
git bisect start
|
||||
git bisect bad HEAD # 매 broken now
|
||||
git bisect good v1.0 # 매 known good
|
||||
|
||||
# 매 매 step:
|
||||
# Run test → 'good' or 'bad'
|
||||
git bisect good
|
||||
|
||||
# 매 끝나면
|
||||
git bisect reset
|
||||
```
|
||||
|
||||
### Time-travel (Redux DevTools)
|
||||
```ts
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
|
||||
const store = configureStore({
|
||||
reducer: rootReducer,
|
||||
devTools: process.env.NODE_ENV !== 'production',
|
||||
});
|
||||
|
||||
// 매 매 action 의 record + 매 replay 가능.
|
||||
```
|
||||
|
||||
### Memory leak detection
|
||||
```js
|
||||
// 매 [[Chrome DevTools 메모리 프로파일링]] 참조
|
||||
|
||||
// 매 3-snapshot technique
|
||||
// 1. Heap snapshot baseline.
|
||||
// 2. 매 suspect action × 5.
|
||||
// 3. Heap snapshot.
|
||||
// 4. Compare → detached DOM, growing objects.
|
||||
```
|
||||
|
||||
### Performance profiling
|
||||
```js
|
||||
// 매 Chrome DevTools Performance tab
|
||||
performance.mark('start_search');
|
||||
const results = expensiveSearch(query);
|
||||
performance.mark('end_search');
|
||||
performance.measure('search', 'start_search', 'end_search');
|
||||
|
||||
// 매 prod: web-vitals + measurement
|
||||
import { onINP } from 'web-vitals';
|
||||
onINP(metric => sendToAnalytics(metric));
|
||||
```
|
||||
|
||||
### Reproducible bug report
|
||||
```markdown
|
||||
## Repro
|
||||
1. ...
|
||||
2. ...
|
||||
|
||||
## Expected
|
||||
...
|
||||
|
||||
## Actual
|
||||
...
|
||||
|
||||
## Environment
|
||||
- Browser: Chrome 130
|
||||
- OS: macOS 15
|
||||
- Build: abc123 (commit: SHA)
|
||||
- User: id 42 (test account)
|
||||
|
||||
## Logs / screenshots
|
||||
[Sentry link, console output, screenshot]
|
||||
```
|
||||
|
||||
### Property-based test (Hypothesis / fast-check)
|
||||
```python
|
||||
from hypothesis import given, strategies as st
|
||||
|
||||
@given(st.integers(), st.integers())
|
||||
def test_addition_commutative(a, b):
|
||||
assert add(a, b) == add(b, a)
|
||||
```
|
||||
|
||||
### LLM-aided debug (stack trace)
|
||||
```python
|
||||
def llm_suggest_fix(error_message, traceback, code_context):
|
||||
prompt = f"""Bug report:
|
||||
Error: {error_message}
|
||||
|
||||
Traceback:
|
||||
{traceback}
|
||||
|
||||
Code context:
|
||||
{code_context}
|
||||
|
||||
Suggest:
|
||||
1. Most likely root cause (1-2 sentences).
|
||||
2. Specific fix (code diff).
|
||||
3. How to prevent recurrence (test, type, validation).
|
||||
|
||||
Be specific, no generic advice."""
|
||||
return llm.generate(prompt)
|
||||
```
|
||||
|
||||
### Bisection (manual binary search)
|
||||
```python
|
||||
def bisect_failing_input(test_fn, inputs):
|
||||
"""매 매 input 의 specific 의 fail 하는 case 의 narrow."""
|
||||
lo, hi = 0, len(inputs) - 1
|
||||
while lo < hi:
|
||||
mid = (lo + hi) // 2
|
||||
if test_fn(inputs[:mid + 1]).failed:
|
||||
hi = mid
|
||||
else:
|
||||
lo = mid + 1
|
||||
return inputs[lo]
|
||||
```
|
||||
|
||||
### Conditional breakpoint
|
||||
```js
|
||||
// 매 Chrome DevTools: 매 매 breakpoint 의 right-click → "Edit breakpoint" → condition
|
||||
// 매 example: user.id === 42 && retryCount > 5
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Reproducible | Debugger + breakpoint |
|
||||
| Production | Sentry + session replay |
|
||||
| Performance | DevTools Performance + APM |
|
||||
| Memory leak | Heap snapshot 3-shot |
|
||||
| Distributed | OpenTelemetry trace |
|
||||
| Bisection | git bisect |
|
||||
| Cannot reproduce | Session replay + log search |
|
||||
| Heisenbug | Differential debug + logging |
|
||||
|
||||
**기본값**: Sentry + DevTools + git bisect + LLM assist.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Software-Engineering]] · [[Debugging]] · [[Observability]]
|
||||
- 변형: [[Sentry]] · [[Datadog]] · [[OpenTelemetry]] · [[LogRocket]]
|
||||
- 응용: [[Chrome DevTools 메모리 프로파일링]] · [[Bottlenecks]] · [[CI_CD 파이프라인 및 IDE 통합 보안]]
|
||||
- Adjacent: [[Concept-Drift]] · [[Quality_Code_Review_Modern]] · [[Bottlenecks]] · [[Code_Smells]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 stack trace analysis. 매 root cause hypothesis. 매 test design.
|
||||
**언제 X**: 매 sensitive data (no upload to LLM).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No reproducer**: 매 hard to fix.
|
||||
- **No observability**: 매 prod 의 silent.
|
||||
- **Print all the things** (no structure): 매 noise.
|
||||
- **No sample / batch**: 매 cost ↑.
|
||||
- **Skip prevention** (no test for fix): 매 regression.
|
||||
- **Privacy 의 ignore** (session replay): 매 PII leak.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Sentry / Datadog docs, OpenTelemetry standard, Chrome DevTools).
|
||||
- 신뢰도 A.
|
||||
- Related: [[Chrome DevTools 메모리 프로파일링]] · [[Bottlenecks]] · [[CI_CD 파이프라인 및 IDE 통합 보안]] · [[Quality_Code_Review_Modern]] · [[Concept-Drift]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — process + tools + 매 Sentry / OTel / git bisect / LLM debug code |
|
||||
|
||||
Reference in New Issue
Block a user