Skip to content

feat: RequestContext 기반 Trace ID / Correlation ID 도입 및 요청 로깅 개선 - #126

Open
labyrinth30 wants to merge 1 commit into
mainfrom
feat/request-trace-id-logging
Open

feat: RequestContext 기반 Trace ID / Correlation ID 도입 및 요청 로깅 개선#126
labyrinth30 wants to merge 1 commit into
mainfrom
feat/request-trace-id-logging

Conversation

@labyrinth30

@labyrinth30 labyrinth30 commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

📌 Description

HTTP 요청별 고유한 식별자(Trace ID / Correlation ID)를 비동기 컨텍스트로 전파하고, Pino 및 Sentry와 연동하여 로깅 및 장애 추적성을 개선합니다.

🚀 주요 변경 사항

  1. RequestContext (AsyncLocalStorage 기반 컨텍스트 관리)

    • src/common/context/request-context.ts: Node.js/Bun의 AsyncLocalStorage를 활용하여 요청 수명주기 동안 requestId, traceId, userId, authUid를 보관 및 비동기 전파.
    • 요청 헤더(x-request-id, x-correlation-id, x-cloud-trace-context, traceparent)를 우선순위에 따라 파싱하고, 없으면 crypto.randomUUID()로 자동 생성.
  2. LoggingMiddleware 고도화

    • 요청 시작 시 RequestContext.run() 안에서 next()를 실행하여 하위 모든 비동기 흐름에 컨텍스트 전파.
    • 응답 헤더에 x-request-id를 자동 주입하여 클라이언트-서버 간 트레이싱 지원.
    • 상태 코드에 따라 로그 레벨 분기 (2xx/3xx -> log, 4xx -> warn, 5xx -> error).
  3. Pino 자동 Mixin 연결 (AppModule)

    • LoggerModule.forRootAsyncmixinRequestContext.get()을 연결하여, 컨트롤러·서비스·필터 등 코드베이스 어디서든 로거를 호출해도 JSON 로그 최상위에 requestId, traceId, userId가 자동 기록됨.
  4. 인증 가드 연동 (CurrentUserGuard, AuthUidGuard)

    • 토큰 검증 및 DB 유저 식별 완료 시 RequestContext.setUserId() / setAuthUid()를 호출하여 인증 이후의 모든 로그에 유저 정보 바인딩.
  5. Sentry 연동 보강 (SentryErrorReporter)

    • Sentry에 예외 캡처 시 request_id 태그와 user 정보를 자동으로 주입하여, Sentry 이슈에서 확인한 request_id로 Cloud Logging 전체 로그를 1:1로 검색 가능.

✅ Done

  • RequestContext 클래스 구현 및 단위 테스트 (7개 케이스)
  • LoggingMiddleware 컨텍스트 연동 / 응답 헤더 주입 / 로그 레벨 분기 및 테스트
  • AppModule Pino mixin 설정
  • CurrentUserGuard, AuthUidGuard 컨텍스트 연동
  • SentryErrorReporter request_id 및 user 태깅 및 테스트
  • 전체 단위 테스트(235 pass) 및 E2E 테스트, Biome lint, Typecheck 통과

Summary by CodeRabbit

  • 신규 기능

    • 요청별 Request ID와 Trace ID를 자동 생성하거나 헤더에서 추출합니다.
    • Request ID를 응답 헤더와 로그에 포함합니다.
    • 인증 사용자 정보를 요청 처리 및 오류 보고에 연결합니다.
  • 개선

    • HTTP 상태 코드에 따라 성공, 경고, 오류 로그 레벨을 구분합니다.
    • 오류 보고서에 요청 ID와 사용자 정보가 추가됩니다.

- AsyncLocalStorage 기반 RequestContext 추가 (requestId, traceId, userId, authUid 보관)
- HTTP 요청 헤더(x-request-id, x-correlation-id, x-cloud-trace-context, traceparent) 파싱 및 UUID fallback 지원
- LoggingMiddleware에서 RequestContext.run 실행 및 응답 헤더(x-request-id) 자동 주입
- 상태 코드별 로그 레벨 분기 (2xx/3xx log, 4xx warn, 5xx error)
- AppModule Pino mixin에 RequestContext를 연결해 모든 로거에서 requestId/userId 자동 기록
- CurrentUserGuard, AuthUidGuard에서 인증 정보 RequestContext에 연동
- SentryErrorReporter에 request_id 및 user 태깅 지원으로 Cloud Logging-Sentry 간 추적성 확보
@coderabbitai

coderabbitai Bot commented Aug 31, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 0c3fd4be-c6cf-4f9d-a91b-1c149e78a2f6

📥 Commits

Reviewing files that changed from the base of the PR and between 713b7fd and d9b4830.

📒 Files selected for processing (9)
  • src/app.module.ts
  • src/common/context/request-context.spec.ts
  • src/common/context/request-context.ts
  • src/common/guards/auth-uid.guard.ts
  • src/common/guards/current-user.guard.ts
  • src/common/middlewares/logging.middleware.spec.ts
  • src/common/middlewares/logging.middleware.ts
  • src/infrastructures/sentry/sentry-reporter.spec.ts
  • src/infrastructures/sentry/sentry-reporter.ts

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

AsyncLocalStorage 기반 RequestContext를 추가했습니다. 로깅 미들웨어가 요청 ID와 Trace ID를 전파하고 상태별 로그를 기록합니다. 인증 가드는 사용자 정보를 저장합니다. pinoHttp와 Sentry는 요청 컨텍스트를 로그와 오류 보고에 포함합니다.

Changes

요청 컨텍스트 기반 관측성

Layer / File(s) Summary
요청 컨텍스트 저장 및 식별자 추출
src/common/context/request-context.ts, src/common/context/request-context.spec.ts
AsyncLocalStorage로 요청 데이터를 유지합니다. 요청 헤더에서 requestIdtraceId를 추출하고, 값이 없으면 생성합니다. 비동기 유지와 식별자 파싱을 테스트합니다.
요청 수명 주기와 로그 전파
src/common/middlewares/logging.middleware.ts, src/common/middlewares/logging.middleware.spec.ts
미들웨어가 컨텍스트를 생성하고 x-request-id 응답 헤더를 설정합니다. 상태 코드에 따라 log, warn, error를 선택합니다. 요청 ID 전파와 로그 레벨을 테스트합니다.
인증 정보 및 오류 보고 연결
src/common/guards/auth-uid.guard.ts, src/common/guards/current-user.guard.ts, src/app.module.ts, src/infrastructures/sentry/sentry-reporter.ts, src/infrastructures/sentry/sentry-reporter.spec.ts
인증 가드가 사용자 ID와 Auth UID를 컨텍스트에 저장합니다. pinoHttp와 Sentry가 요청 컨텍스트의 식별자를 기록합니다. Sentry 태그, 사용자 정보, 추가 데이터를 테스트합니다.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: 🔵 Low · up to d9b48

Client-supplied request and trace identifiers are now echoed and propagated into logs and error reports without strict validation, which can allow misleading request correlation or excess telemetry cardinality. The PR is mergeable with explicit owner awareness and follow-up to validate identifiers and distinguish trusted upstream values from server-generated IDs.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant LoggingMiddleware
  participant RequestContext
  participant AuthGuards
  participant LoggerAndSentry

  Client->>LoggingMiddleware: HTTP request with identity headers
  LoggingMiddleware->>RequestContext: extractOrCreate(req)
  LoggingMiddleware->>RequestContext: run({ requestId, traceId }, next)
  LoggingMiddleware->>AuthGuards: execute authentication
  AuthGuards->>RequestContext: setUserId(), setAuthUid()
  LoggingMiddleware->>LoggerAndSentry: record request outcome
  LoggerAndSentry->>RequestContext: read request and user identifiers
Loading

Suggested reviewers: kkardy, minsour, sudosubin

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed 제목은 RequestContext 기반 Trace ID 및 Correlation ID 도입과 요청 로깅 개선이라는 주요 변경 사항을 구체적으로 요약합니다.
Description check ✅ Passed 설명은 주요 변경 사항과 완료된 작업을 충분히 포함합니다. 템플릿의 Related Issue와 Notes 섹션은 없지만, 핵심 정보가 대부분 작성되어 있습니다.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/request-trace-id-logging

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@labyrinth30 labyrinth30 self-assigned this Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant