1. 準備工作
導入必要的庫
import contextvars
import time
from typing import Any, Optional, Dict, List, Union
from dataclasses import dataclass, field
2. 定義上下文變量
# 定義兩個上下文變量,存儲當前 Span 和 Trace
_current_span: contextvars.ContextVar[Optional["Span"]] = contextvars.ContextVar("current_span", default=None
)_current_trace: contextvars.ContextVar[Optional["Trace"]] = contextvars.ContextVar("current_trace", default=None
)
3. 數據模型定義
3.1 SpanContext 類
@dataclass
class SpanContext:"""Span 的上下文信息(用于跨進程傳遞)"""trace_id: strspan_id: stris_remote: bool = False
3.2 Span 類
@dataclass
class Span:"""表示一個操作的時間段追蹤"""name: strcontext: SpanContextparent: Optional["Span"] = Nonestart_time: float = field(default_factory=time.time)end_time: Optional[float] = Noneattributes: Dict[str, Any] = field(default_factory=dict)events: List[Dict[str, Any]] = field(default_factory=list)status: str = "UNSET"def end(self, status: str = "OK") -> None:"""結束 Span 并記錄狀態"""self.end_time = time.time()self.status = statusdef add_event(self, name: str, attributes: Optional[Dict[str, Any]] = None) -> None:"""添加事件到 Span"""self.events.append({"name": name,"timestamp": time.time(),"attributes": attributes or {}})def __enter__(self) -> "Span":"""支持 with 語句"""return selfdef __exit__(self, exc_type, exc_val, exc_tb) -> None:"""自動結束 Span"""self.end("ERROR" if exc_type else "OK")
3.3 Trace 類
@dataclass
class Trace:"""完整的追蹤鏈"""root_span: Spanspans: List[Span] = field(default_factory=list)def add_span(self, span: Span) -> None:"""添加 Span 到 Trace"""self.spans.append(span)
4. 追蹤 API 實現
4.1 輔助函數
def generate_id() -> str:"""生成追蹤ID(簡化版)"""return f"id-{int(time.time() * 1000)}"def get_current_span() -> Optional[Span]:"""獲取當前 Span"""return _current_span.get()def get_current_trace() -> Optional[Trace]:"""獲取當前 Trace"""return _current_trace.get()
4.2 核心函數
def start_span(name: str, attributes: Optional[Dict[str, Any]] = None) -> Span:"""創建并激活一個新 Span:param name: Span 名稱:param attributes: 附加屬性:return: 新創建的 Span"""parent = get_current_span()context = SpanContext(trace_id=parent.context.trace_id if parent else generate_id(),span_id=generate_id())span = Span(name=name, context=context, parent=parent)if attributes:span.attributes.update(attributes)# 設置當前 Span_current_span.set(span)# 如果是根 Span,則創建 Traceif parent is None:trace = Trace(root_span=span)_current_trace.set(trace)else:trace = get_current_trace()if trace:trace.add_span(span)return spandef end_span(status: str = "OK") -> None:"""結束當前 Span 并返回父 Span"""current = get_current_span()if current:current.end(status)_current_span.set(current.parent)
5. 數據導出器
class ConsoleExporter:"""將追蹤數據打印到控制臺"""@staticmethoddef export(trace: Trace) -> None:print("\n=== Exporting Trace ===")print(f"Trace ID: {trace.root_span.context.trace_id}")for span in trace.spans:duration = (span.end_time or time.time()) - span.start_timeprint(f"Span: {span.name} ({duration:.3f}s), Status: {span.status}")
6. 使用示例
6.1 同步代碼示例
# 示例 1: 同步代碼
with start_span("main_operation", {"type": "sync"}):# 當前 Span 是 "main_operation"with start_span("child_operation"):# 當前 Span 是 "child_operation"get_current_span().add_event("processing_start")time.sleep(0.1)get_current_span().add_event("processing_end")# 手動創建 Spanspan = start_span("manual_span")time.sleep(0.05)span.end()# 導出追蹤數據
if trace := get_current_trace():ConsoleExporter.export(trace)
=== Exporting Trace ===
Trace ID: id-1751643441896
Span: main_operation (0.152s), Status: OK
Span: child_operation (0.101s), Status: OK
Span: manual_span (0.050s), Status: OK
6.2 異步代碼示例(可選)
import asyncioasync def async_task():with start_span("async_operation"):print(f"Current span: {get_current_span().name}")await asyncio.sleep(0.1)async def main():tasks = [async_task() for _ in range(3)]await asyncio.gather(*tasks)# 運行異步示例
asyncio.run(main())
Current span: async_operation
Current span: async_operation
Current span: async_operation
7. 可視化追蹤數據(可選)
import matplotlib.pyplot as pltdef visualize_trace(trace: Trace):fig, ax = plt.subplots(figsize=(10, 6))for i, span in enumerate(trace.spans):duration = (span.end_time or time.time()) - span.start_timeax.barh(span.name, duration, left=span.start_time, alpha=0.6)ax.text(span.start_time, i, f"{duration:.3f}s", va='center')ax.set_xlabel('Time')ax.set_title('Trace Visualization')plt.show()if trace := get_current_trace():visualize_trace(trace)
代碼:https://github.com/zhouruiliangxian/Awesome-demo/blob/main/Distributed-Tracing/%E7%AE%80%E6%98%93%E5%88%86%E5%B8%83%E5%BC%8F%E8%BF%BD%E8%B8%AA%E7%B3%BB%E7%BB%9F.ipynb