[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -4,113 +4,227 @@ title: Logging Diagnostics
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-LOGGING-DIAGNOSTICS, 로그, Logs, 로깅, 로깅 전략, 중앙 집중식 로깅, 에러 기록]
aliases: [Logging, Application Logging, Diagnostic Logging]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Observability, Logging, Diagnostics, Architecture, Microservices]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
confidence_score: 0.9
verification_status: applied
tags: [observability, logging, diagnostics, sre]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: pino
---
# [[시스템 로깅과 런타임 진단 (Logging & Diagnostics)]]
# Logging Diagnostics
## 1. 개요
로그(Logs)는 시스템 실행 중에 발생하는 주요 이벤트, 상태 변화, 에러 메시지 및 예외 상황을 기록한 데이터다. 단순한 텍스트 기록을 넘어, 정적 코드 분석만으로는 파악할 수 없는 시스템의 동적인 특성과 런타임 동작 흐름을 이해하게 해주는 핵심적인 진단 도구이자, 관측 가능성(Observability)의 기반이 된다.
## 매 한 줄
> **"매 structured event 의 production runtime 의 X-ray"**. Application logging 은 매 incident 의 forensic record + 매 system behavior 의 narrative. 2026 best practice: **structured JSON logs + OpenTelemetry semantic conventions + sampling at scale + cardinality discipline**. Plain text logs 는 매 deprecated; loggers 는 매 trace context 와 correlation.
## 2. 주요 로깅 전략
- **중앙 집중식 로깅 (Centralized Logging)**: 분산된 마이크로서비스 환경에서 각 서비스의 로그를 한곳(예: ELK Stack, Splunk)으로 수집하여 시스템 전체의 가시성을 확보하고 상관관계 분석 수행.
- **구조화된 로깅 (Structured Logging)**: 단순 텍스트가 아닌 JSON 등의 정형화된 포맷으로 기록하여, 로그 분석 도구에서 필터링, 집계, 검색이 용이하도록 구성.
- **로그 레벨 관리**: 상황에 따라 `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL` 등 레벨을 구분하여 기록함으로써 정보의 중요도 식별 및 운영 비용 최적화.
- **능동적 로깅 (Proactive Logging)**: 코드 분석 시 의도적으로 추가 로그를 삽입하여 데이터 변환이나 조건문 분기 등 특정 로직의 실행 여부를 실전적으로 검증.
## 매 핵심
## 3. 엔지니어링 가치
- **장애 원인 규명 (Root Cause Analysis)**: 에러 발생 시 출력되는 스택 트레이스와 이전 이벤트 로그를 결합하여, 문제가 발생한 시점의 맥락과 원인을 정확히 추적.
- **동적 코드 해독**: 낯선 코드베이스에 온보딩할 때, 시스템에 다양한 입력값을 주입하고 로그의 변화를 관찰함으로써 내부 동작 방식과 비즈니스 로직 학습 가속화.
- **보안 및 감사 (Audit)**: 비정상적인 접근 시도나 데이터 변경 이력을 기록하여 보안 사고 예방 및 규정 준수(Compliance) 증명.
### 매 3 pillars (observability)
- **Logs**: discrete events, high cardinality, narrative.
- **Metrics**: aggregated time-series, low cardinality, dashboards/alerts.
- **Traces**: causal chain across services.
- 매 modern unified backbone: OpenTelemetry → Loki/Tempo/Prometheus 또는 Datadog/Honeycomb.
## 4. 트레이드오프 및 주의사항
- **성능 오버헤드**: 과도한 로깅은 I/O 부하를 일으키고 애플리케이션의 처리 속도를 늦출 수 있음. 샘플링(Sampling)이나 비동기 로깅 방식 고려.
- **민감 정보 유출**: 로그에 비밀번호, 개인정보, API 키 등이 포함되지 않도록 마스킹(Masking) 및 필터링 정책 필수 적용.
- **알림 피로 (Alert Fatigue)**: 너무 많은 경고 로그가 생성되면 중요한 장애 징후를 놓칠 수 있다. 로그를 기반으로 한 알림 정책은 정교하게 설계되어야 함.
### 매 log levels
- **TRACE**: 매 fine-grained internal state (off in prod).
- **DEBUG**: 매 development diagnostics (sampled or off in prod).
- **INFO**: 매 business event, lifecycle (default level).
- **WARN**: 매 degraded but recoverable.
- **ERROR**: 매 actionable failure — page-worthy candidate.
- **FATAL**: 매 process-terminating.
## 5. 지식 연결 (Related)
- [[Call_Stack_Analysis]]: 로그에 기록되는 스택 트레이스의 원리 및 분석.
- [[Intentional_Failure_Induction]]: 분석용 로그를 얻기 위해 고의로 에러를 유발하는 기법.
- [[Security_Posture_Management]]: 보안 로그를 통합 관리하는 관제 체계.
### 매 structured logging principles
1. JSON output (or logfmt).
2. 매 fixed schema: `timestamp, level, service, trace_id, span_id, message, ...attrs`.
3. Correlation IDs propagated (W3C Trace Context).
4. 매 PII redaction at source.
5. Sampling for high-volume paths.
6. 매 cardinality discipline — no unbounded values in indexed fields.
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 시스템의 상태를 투명하게 관측하고 런타임 결함을 신속하게 진단하기 위한 전사 로깅 표준 및 운영 가이드라인 정립.
### 매 응용
1. Incident investigation (search by trace_id).
2. Audit trail (compliance — separate stream).
3. Business event analytics (BI pipeline ingestion).
4. SLO error budget calculation.
5. Anomaly detection input.
## 📌 한 줄 통찰 (The Karpathy Summary)
## 💻 패턴
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
### 1. Pino (Node.js, fast structured logging)
```typescript
import pino from "pino";
## 📖 구조화된 지식 (Synthesized Content)
export const logger = pino({
level: process.env.LOG_LEVEL ?? "info",
redact: ["password", "*.authorization", "creditCard"],
formatters: {
level: (label) => ({ level: label }),
},
base: {
service: "checkout",
env: process.env.NODE_ENV,
version: process.env.GIT_SHA,
},
});
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
logger.info({ userId, orderId, amount }, "order placed");
// {"level":"info","time":1710000000,"service":"checkout","userId":"u1",...}
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. OpenTelemetry log correlation
```typescript
import { trace } from "@opentelemetry/api";
import pino from "pino";
**선택 A를 써야 할 때:**
- *(TODO)*
const baseLogger = pino();
**선택 B를 써야 할 때:**
- *(TODO)*
export function getLogger() {
const span = trace.getActiveSpan();
const ctx = span?.spanContext();
return baseLogger.child({
trace_id: ctx?.traceId,
span_id: ctx?.spanId,
});
}
**기본값:**
> *(TODO)*
// Usage
getLogger().error({ err }, "payment failed");
// Now searchable by trace_id across services.
```
## ❌ 안티패턴 (Anti-Patterns)
### 3. Python structlog
```python
import structlog
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer(),
],
)
log = structlog.get_logger()
structlog.contextvars.bind_contextvars(request_id=req_id, user_id=uid)
log.info("checkout_started", cart_size=len(cart))
```
### 4. Sampling (head + tail)
```typescript
// Head sampling: decide at request entry
function shouldLog(req: Request): boolean {
if (req.url.startsWith("/health")) return false; // drop healthchecks
if (req.headers["x-debug"]) return true; // force on
return Math.random() < 0.01; // 1% sample for /api/*
}
// Tail sampling (in OTel collector): keep all errors + slow + 1% baseline
```
### 5. Error logging with stack + cause
```typescript
try {
await chargeCard(order);
} catch (err) {
logger.error({
err: { message: err.message, stack: err.stack, cause: err.cause },
orderId: order.id,
customerId: order.customerId,
}, "charge failed");
throw err;
}
```
### 6. Redaction (PII safety)
```typescript
const SENSITIVE = /(\b\d{16}\b|\b\d{3}-\d{2}-\d{4}\b)/g; // CC, SSN
function sanitize(obj: any): any {
const json = JSON.stringify(obj);
return JSON.parse(json.replace(SENSITIVE, "[REDACTED]"));
}
logger.info(sanitize(payload), "received webhook");
```
### 7. Audit log (separate stream)
```typescript
const audit = pino({
level: "info",
base: { stream: "audit" },
// separate transport → tamper-evident store (S3 + object lock)
});
audit.info({
actor: user.id,
action: "user.delete",
target: targetId,
ip: req.ip,
outcome: "success",
}, "audit");
```
### 8. Go slog (stdlib, 1.21+)
```go
import "log/slog"
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger)
slog.Info("order placed",
"user_id", userID,
"order_id", orderID,
"amount", amount,
)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 새 service | Structured JSON + OTel correlation. |
| High-volume path (>1k rps) | Head sampling + tail sampling. |
| Compliance / audit | Separate audit stream + immutable store. |
| Legacy plain-text logs | Parse → enrich → forward (Vector, Fluent Bit). |
| Edge / IoT | Compact binary (CBOR) + batched upload. |
| Real-time alerting on log content | Stream → Loki/ELK with regex rules. |
**기본값**: 2026 의 새 서비스는 매 OTel logs + structured JSON + Pino/structlog/slog. 매 plain text 의 X.
## 🔗 Graph
- 부모: [[Observability]] · [[SRE Practices]]
- 변형: [[Audit Logging]] · [[Access Logging]] · [[Metric Logging]]
- 응용: [[Incident Response]] · [[SLO Tracking]] · [[Compliance Auditing]]
- Adjacent: [[OpenTelemetry]] · [[Distributed Tracing]] · [[Metrics]]
## 🤖 LLM 활용
**언제**: log schema design, sampling strategy, log-to-trace correlation, redaction policy review.
**언제 X**: 매 metric/trace 만 필요한 경우 (logs 의 cost > value), 매 single-developer side project (basic console.log 충분).
## ❌ 안티패턴
- **String interpolation logs**: `log.info("user " + id + " did " + action)` — 매 unparseable, 매 search 불가. 매 structured fields 사용.
- **PII leak**: 매 redaction 부재 → 매 GDPR breach.
- **Unbounded cardinality**: 매 user_email 을 indexed field 로 → 매 storage explosion.
- **Logging in tight loop**: 매 hot path 의 매 iter 마다 log → 매 IO bottleneck.
- **Catch and silent log**: `} catch (e) { logger.error(e); }` 에서 매 context 부재 — orderId/userId 같이 add.
- **Plain text in 2026**: 매 grep-only logs — search/correlation 매 painful.
- **No trace correlation**: 매 service 마다 isolated logs — 매 incident 시 매 cross-service narrative 의 manual 재구성.
## 🧪 검증 / 중복
- Verified (OpenTelemetry Logs spec, Google SRE Book Ch.6, Pino/structlog official docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — structured logging + OTel correlation + sampling/redaction patterns |