Skip to content

fix(logging): read user_email from span attributes, not a ContextVar - #95

Merged
wonzz merged 1 commit into
mainfrom
fix/loki-log-user-email-threadpool
Jul 3, 2026
Merged

wonzz merged 1 commit into
mainfrom
fix/loki-log-user-email-threadpool

Conversation

@0206pdh

@0206pdh 0206pdh commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Summary

  • fix(logging): inject user_email into structured log output #94 에서 추가한 ContextVar 기반 user_email 로그 주입이 실제로는 동작하지 않는 버그였음 (이미지 재배포해도 여전히 검색 안 되는 원인)
  • get_current_user()는 def(동기)라 FastAPI/anyio가 스레드풀에서 실행함 → anyio.to_thread.run_sync는 contextvars.copy_context()로 컨텍스트 복사본을 만들어 그 안에서 실행 → ContextVar.set()이 원래 요청 컨텍스트로 절대 전파되지 않음 (실측 재현 완료)
  • span.set_attribute()는 이미 만들어진 span 객체를 참조로 공유하므로 스레드 경계 영향을 안 받음 → 기존 user.id/user.email 트레이스 검색은 정상 동작했던 이유
  • ContextVar/set_request_user_email 제거하고, 포매터가 trace.get_current_span().attributes에서 직접 user.email을 읽도록 변경

Test plan

  • anyio.to_thread.run_sync 경계에서 ContextVar.set()이 전파 안 되는 것 재현 확인
  • opentelemetry.sdk.trace.Span.attributes가 set_attribute 이후 값을 정확히 반영하는 것 확인 (recording span), non-recording span에서는 안전하게 빈 값 처리되는 것 확인
  • 배포 후 실제 로그 stdout에 user_email 필드가 찍히는지 확인
  • VOC UI Pod Logs에서 user.email 검색으로 실제 로그 조회되는지 확인

이전 PR(#94)의 ContextVar 방식이 실제로는 동작하지 않는 버그였다.
get_current_user()는 동기 함수(def)라 FastAPI가 스레드풀에서 실행하는데,
anyio.to_thread.run_sync는 contextvars.copy_context()로 복사본을 만들어
그 안에서 실행하므로 ContextVar.set()이 원래 요청 컨텍스트로 전파되지
않는다. 즉 이미지를 새로 배포해도 로그에 user_email이 절대 찍히지 않았다.

span.set_attribute()는 이미 값이 채워진 span 객체 자체를 참조로 공유하기
때문에 스레드 경계와 무관하게 작동한다 (user.id/user.email 트레이스 검색이
이미 되던 이유). 그래서 별도 ContextVar 없이 포매터에서 현재 span의
attributes를 직접 읽도록 변경.
@wonzz
wonzz self-requested a review July 3, 2026 03:32
@wonzz
wonzz merged commit 7cc5f4b into main Jul 3, 2026
1 check passed
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.

2 participants