Starts a new trace (root span) and returns its context. Args: trace_name: Name for the trace (e.g., "session", "my_custom_trace"). tags: Optional tags to attach to the trace span. is_init_trace: Internal flag to mark if this is the automatically
(
self, trace_name: str = "session", tags: Optional[dict | list] = None, is_init_trace: bool = False
)
| 379 | # No need to register them here anymore |
| 380 | |
| 381 | def start_trace( |
| 382 | self, trace_name: str = "session", tags: Optional[dict | list] = None, is_init_trace: bool = False |
| 383 | ) -> Optional[TraceContext]: |
| 384 | """ |
| 385 | Starts a new trace (root span) and returns its context. |
| 386 | |
| 387 | Args: |
| 388 | trace_name: Name for the trace (e.g., "session", "my_custom_trace"). |
| 389 | tags: Optional tags to attach to the trace span. |
| 390 | is_init_trace: Internal flag to mark if this is the automatically started init trace. |
| 391 | |
| 392 | Returns: |
| 393 | A TraceContext object containing the span and context token, or None if not initialized. |
| 394 | """ |
| 395 | if not self.initialized: |
| 396 | logger.warning("Global tracer not initialized. Cannot start trace.") |
| 397 | return None |
| 398 | |
| 399 | # Build trace attributes |
| 400 | attributes = get_trace_attributes(tags=tags) |
| 401 | # Include system metadata only for the default session trace |
| 402 | if trace_name == "session": |
| 403 | attributes.update(get_system_resource_attributes()) |
| 404 | |
| 405 | # make_span creates and starts the span, and activates it in the current context |
| 406 | # It returns: span, context_object, context_token |
| 407 | span, _, context_token = self.make_span(trace_name, span_kind=SpanKind.SESSION, attributes=attributes) |
| 408 | logger.debug(f"Trace '{trace_name}' started with span ID: {span.get_span_context().span_id}") |
| 409 | |
| 410 | # Log the session replay URL for this new trace |
| 411 | try: |
| 412 | log_trace_url(span, title=trace_name) |
| 413 | except Exception as e: |
| 414 | logger.warning(f"Failed to log trace URL for '{trace_name}': {e}") |
| 415 | |
| 416 | trace_context = TraceContext(span, token=context_token, is_init_trace=is_init_trace) |
| 417 | |
| 418 | # Track the active trace |
| 419 | with self._traces_lock: |
| 420 | try: |
| 421 | trace_id = f"{span.get_span_context().trace_id:x}" |
| 422 | except (TypeError, ValueError): |
| 423 | # Handle case where span is mocked or trace_id is not a valid integer |
| 424 | trace_id = str(span.get_span_context().trace_id) |
| 425 | self._active_traces[trace_id] = trace_context |
| 426 | logger.debug(f"Added trace {trace_id} to active traces. Total active: {len(self._active_traces)}") |
| 427 | |
| 428 | return trace_context |
| 429 | |
| 430 | def end_trace( |
| 431 | self, trace_context: Optional[TraceContext] = None, end_state: Union[Any, StatusCode, str] = None |