|
| 1 | +"""Internal utilities for Temporal logging. |
| 2 | +
|
| 3 | +This module is internal and may change at any time. |
| 4 | +""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import json |
| 9 | +from collections.abc import Mapping, MutableMapping |
| 10 | +from typing import Any, Literal |
| 11 | + |
| 12 | +TemporalLogExtraMode = Literal["dict", "flatten", "json"] |
| 13 | +"""Mode controlling how Temporal context is added to log record extra. |
| 14 | +
|
| 15 | +Values: |
| 16 | + dict: (default) Add context as a nested dictionary under a single key. |
| 17 | + This is the original behavior. Suitable for logging handlers that |
| 18 | + support nested structures. |
| 19 | + flatten: Add each context field as a separate top-level key with a |
| 20 | + namespaced prefix. Values that are not primitives (str/int/float/bool) |
| 21 | + are converted to strings. This mode is recommended for OpenTelemetry |
| 22 | + and other logging pipelines that require flat, scalar attributes. |
| 23 | + json: Add context as a JSON string under a single key. Useful when |
| 24 | + downstream systems expect string values but you want structured data. |
| 25 | +""" |
| 26 | + |
| 27 | + |
| 28 | +def _apply_temporal_context_to_extra( |
| 29 | + extra: MutableMapping[str, Any], |
| 30 | + *, |
| 31 | + key: str, |
| 32 | + prefix: str, |
| 33 | + ctx: Mapping[str, Any], |
| 34 | + mode: TemporalLogExtraMode, |
| 35 | +) -> None: |
| 36 | + """Apply temporal context to log record extra based on the configured mode. |
| 37 | +
|
| 38 | + Args: |
| 39 | + extra: The mutable extra dict to update. |
| 40 | + key: The key to use for dict/json modes (e.g., "temporal_workflow"). |
| 41 | + prefix: The prefix to use for flatten mode keys (e.g., "temporal.workflow"). |
| 42 | + ctx: The context mapping containing temporal fields. |
| 43 | + mode: The mode controlling how context is added. |
| 44 | + """ |
| 45 | + if mode == "dict": |
| 46 | + extra[key] = dict(ctx) |
| 47 | + elif mode == "json": |
| 48 | + extra[key] = json.dumps(ctx, separators=(",", ":"), default=str) |
| 49 | + elif mode == "flatten": |
| 50 | + for k, v in ctx.items(): |
| 51 | + # Ensure value is a primitive type safe for OTel attributes |
| 52 | + if not isinstance(v, (str, int, float, bool, type(None))): |
| 53 | + v = str(v) |
| 54 | + extra[f"{prefix}.{k}"] = v |
| 55 | + else: |
| 56 | + # Fallback to dict for any unknown mode (shouldn't happen with typing) |
| 57 | + extra[key] = dict(ctx) |
| 58 | + |
| 59 | + |
| 60 | +def _update_temporal_context_in_extra( |
| 61 | + extra: MutableMapping[str, Any], |
| 62 | + *, |
| 63 | + key: str, |
| 64 | + prefix: str, |
| 65 | + update_ctx: Mapping[str, Any], |
| 66 | + mode: TemporalLogExtraMode, |
| 67 | +) -> None: |
| 68 | + """Update existing temporal context in extra with additional fields. |
| 69 | +
|
| 70 | + This is used when adding update info to existing workflow context. |
| 71 | +
|
| 72 | + Args: |
| 73 | + extra: The mutable extra dict to update. |
| 74 | + key: The key used for dict/json modes (e.g., "temporal_workflow"). |
| 75 | + prefix: The prefix used for flatten mode keys (e.g., "temporal.workflow"). |
| 76 | + update_ctx: Additional context fields to add/update. |
| 77 | + mode: The mode controlling how context is added. |
| 78 | + """ |
| 79 | + if mode == "dict": |
| 80 | + extra.setdefault(key, {}).update(update_ctx) |
| 81 | + elif mode == "json": |
| 82 | + # For JSON mode, we need to parse, update, and re-serialize |
| 83 | + existing = extra.get(key) |
| 84 | + if existing is not None: |
| 85 | + try: |
| 86 | + existing_dict = json.loads(existing) |
| 87 | + existing_dict.update(update_ctx) |
| 88 | + extra[key] = json.dumps( |
| 89 | + existing_dict, separators=(",", ":"), default=str |
| 90 | + ) |
| 91 | + except (json.JSONDecodeError, TypeError): |
| 92 | + # If parsing fails, just create a new JSON object with update_ctx |
| 93 | + extra[key] = json.dumps( |
| 94 | + dict(update_ctx), separators=(",", ":"), default=str |
| 95 | + ) |
| 96 | + else: |
| 97 | + extra[key] = json.dumps( |
| 98 | + dict(update_ctx), separators=(",", ":"), default=str |
| 99 | + ) |
| 100 | + elif mode == "flatten": |
| 101 | + for k, v in update_ctx.items(): |
| 102 | + # Ensure value is a primitive type safe for OTel attributes |
| 103 | + if not isinstance(v, (str, int, float, bool, type(None))): |
| 104 | + v = str(v) |
| 105 | + extra[f"{prefix}.{k}"] = v |
| 106 | + else: |
| 107 | + # Fallback to dict for any unknown mode |
| 108 | + extra.setdefault(key, {}).update(update_ctx) |
0 commit comments