ForcePilot/backend/package/yuxi/utils/trace_context.py
Kris ba2b27961f style(trace_context): 格式化代码行,简化变量定义语句
调整trace_context.py里的trace id上下文变量定义格式,合并多行代码为一行提升可读性
2026-07-07 16:21:58 +08:00

40 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""请求级 trace_id 上下文(共享模块)。
通过 ContextVar 存储每个请求的 trace_id供异常处理器、日志适配器
等跨层读取。中间件入口生成(或从 X-Request-Id header 读取)。
本模块为 server 层与 channels 层共享的 trace_id 机制,确保两套
ContextVarserver 层 ``_trace_id_var`` 与 channels 层 ``_current_span``
保持同步。
"""
from __future__ import annotations
import uuid
from contextvars import ContextVar
_trace_id_var: ContextVar[str | None] = ContextVar("yuxi_request_trace_id", default=None)
def set_trace_id(trace_id: str) -> None:
"""设置当前请求的 trace_id。"""
_trace_id_var.set(trace_id)
def get_trace_id() -> str | None:
"""获取当前请求的 trace_id未设置时返回 None。"""
return _trace_id_var.get()
def generate_trace_id() -> str:
"""生成新的 trace_iduuid4 十六进制)。"""
return uuid.uuid4().hex
def reset_trace_id() -> None:
"""请求结束时重置 trace_id。
ContextVar 在请求结束后自动回收,显式重置作为保险。
"""
_trace_id_var.set(None)