Context Model
Logger reference

Request Context Model

RequestContext is a lightweight dataclass used to attach request-scoped metadata to structured logs. It is designed to improve traceability across distributed and conversational systems.

1. Behavior and Context

The class holds common tracing identifiers:

  • request_id
  • conversation_id
  • user_id
  • session_id
  • endpoint

If request_id is not provided, the class auto-generates one in __post_init__ as a 12-character hex value derived from uuid4.

2. Purpose

  • Traceability: Correlate all logs generated by a single request.
  • Cross-System Correlation: Carry user/session identifiers into external observability sinks.
  • Low Ceremony: Dataclass API with deterministic serialization.

3. High-Level API & Examples

Example 1: Create Context with Auto Request ID

python
from jazzmine.logging import RequestContext

ctx = RequestContext(
    conversation_id="conv_9f3",
    user_id="u_123",
    endpoint="/v1/chat",
)

print(ctx.request_id)  # auto-generated
print(ctx.to_dict())

Example 2: Explicit Request ID (Upstream Trace ID)

python
from jazzmine.logging import RequestContext

ctx = RequestContext(
    request_id="trace_abc123",
    session_id="sess_001",
)

payload = ctx.to_dict()
# payload includes all fields, including None values

4. Detailed Class Functionality

__post_init__()

Runs after dataclass initialization:

  • If request_id is None, sets it to uuid.uuid4().hex[:12].

to_dict() -> Dict[str, Any]

Returns asdict(self) as a plain dict.

  • Includes None fields by design.
  • Useful for direct **kwargs enrichment in structured logging calls.

5. Error Handling

This module does not define custom exceptions or raise explicit errors under normal use.

6. Remarks

  • If your tracing platform requires a specific ID format, provide request_id explicitly.
  • Including None keys can simplify schema consistency for downstream log processors.