Blame view

translation/logging_utils.py 1.08 KB
14e67b71   tangwang   分句后的 batching 现在是...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  """Shared translation logging context helpers."""
  
  from __future__ import annotations
  
  import contextvars
  import logging
  import uuid
  from typing import Optional
  
  
  _translation_request_id_var: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar(
      "translation_request_id",
      default=None,
  )
  
  
  def current_translation_request_id() -> str:
      return _translation_request_id_var.get() or "-1"
  
  
  def bind_translation_request_id(request_id: Optional[str] = None) -> tuple[str, contextvars.Token]:
      raw_value = str(request_id or "").strip()
      normalized = raw_value[:32] if raw_value else str(uuid.uuid4())[:8]
      return normalized, _translation_request_id_var.set(normalized)
  
  
  def reset_translation_request_id(token: contextvars.Token) -> None:
      _translation_request_id_var.reset(token)
  
  
  class TranslationRequestFilter(logging.Filter):
      """Inject a request id into translator logs when one is available."""
  
      def filter(self, record: logging.LogRecord) -> bool:
          if not hasattr(record, "reqid"):
              record.reqid = current_translation_request_id()
          return True