|
| 1 | +"""Helper utilities for adding telemetry spans to Azure SDK operations. |
| 2 | +
|
| 3 | +This module provides decorators and context managers for adding OpenTelemetry |
| 4 | +spans to Azure SDK calls (CosmosDB, Blob Storage, etc.) without interfering |
| 5 | +with Semantic Kernel's async generators. |
| 6 | +
|
| 7 | +Example usage: |
| 8 | + from common.telemetry.telemetry_helper import trace_operation |
| 9 | + |
| 10 | + @trace_operation("cosmosdb_query") |
| 11 | + async def query_items(self, query: str): |
| 12 | + # Your CosmosDB query here |
| 13 | + pass |
| 14 | +""" |
| 15 | + |
| 16 | +import functools |
| 17 | +from contextlib import asynccontextmanager, contextmanager |
| 18 | +from typing import Any, Optional |
| 19 | + |
| 20 | +from opentelemetry import trace |
| 21 | +from opentelemetry.trace import Status, StatusCode |
| 22 | + |
| 23 | + |
| 24 | +def get_tracer(name: str = __name__): |
| 25 | + """Get a tracer instance for the given name.""" |
| 26 | + return trace.get_tracer(name) |
| 27 | + |
| 28 | + |
| 29 | +def trace_operation(operation_name: str, attributes: Optional[dict] = None): |
| 30 | + """Decorator to add telemetry span to a function or method. |
| 31 | + |
| 32 | + Args: |
| 33 | + operation_name: Name of the operation for the span |
| 34 | + attributes: Optional dictionary of attributes to add to the span |
| 35 | + |
| 36 | + Example: |
| 37 | + @trace_operation("batch_processing", {"service": "sql_agents"}) |
| 38 | + async def process_batch(batch_id: str): |
| 39 | + # Your code here |
| 40 | + pass |
| 41 | + """ |
| 42 | + def decorator(func): |
| 43 | + @functools.wraps(func) |
| 44 | + async def async_wrapper(*args, **kwargs): |
| 45 | + tracer = get_tracer(func.__module__) |
| 46 | + with tracer.start_as_current_span(operation_name) as span: |
| 47 | + # Add custom attributes if provided |
| 48 | + if attributes: |
| 49 | + for key, value in attributes.items(): |
| 50 | + span.set_attribute(key, str(value)) |
| 51 | + |
| 52 | + # Add function arguments as attributes (optional, for debugging) |
| 53 | + span.set_attribute("function", func.__name__) |
| 54 | + |
| 55 | + try: |
| 56 | + result = await func(*args, **kwargs) |
| 57 | + span.set_status(Status(StatusCode.OK)) |
| 58 | + return result |
| 59 | + except Exception as e: |
| 60 | + span.record_exception(e) |
| 61 | + span.set_status(Status(StatusCode.ERROR, str(e))) |
| 62 | + raise |
| 63 | + |
| 64 | + @functools.wraps(func) |
| 65 | + def sync_wrapper(*args, **kwargs): |
| 66 | + tracer = get_tracer(func.__module__) |
| 67 | + with tracer.start_as_current_span(operation_name) as span: |
| 68 | + if attributes: |
| 69 | + for key, value in attributes.items(): |
| 70 | + span.set_attribute(key, str(value)) |
| 71 | + |
| 72 | + span.set_attribute("function", func.__name__) |
| 73 | + |
| 74 | + try: |
| 75 | + result = func(*args, **kwargs) |
| 76 | + span.set_status(Status(StatusCode.OK)) |
| 77 | + return result |
| 78 | + except Exception as e: |
| 79 | + span.record_exception(e) |
| 80 | + span.set_status(Status(StatusCode.ERROR, str(e))) |
| 81 | + raise |
| 82 | + |
| 83 | + # Return appropriate wrapper based on function type |
| 84 | + if asyncio.iscoroutinefunction(func): |
| 85 | + return async_wrapper |
| 86 | + else: |
| 87 | + return sync_wrapper |
| 88 | + |
| 89 | + return decorator |
| 90 | + |
| 91 | + |
| 92 | +@asynccontextmanager |
| 93 | +async def trace_context(operation_name: str, attributes: Optional[dict] = None): |
| 94 | + """Async context manager for adding telemetry span to a code block. |
| 95 | + |
| 96 | + Args: |
| 97 | + operation_name: Name of the operation for the span |
| 98 | + attributes: Optional dictionary of attributes to add to the span |
| 99 | + |
| 100 | + Example: |
| 101 | + async with trace_context("cosmosdb_batch_query", {"batch_id": batch_id}): |
| 102 | + results = await database.query_items(query) |
| 103 | + # Your code here |
| 104 | + """ |
| 105 | + tracer = get_tracer() |
| 106 | + with tracer.start_as_current_span(operation_name) as span: |
| 107 | + if attributes: |
| 108 | + for key, value in attributes.items(): |
| 109 | + span.set_attribute(key, str(value)) |
| 110 | + |
| 111 | + try: |
| 112 | + yield span |
| 113 | + span.set_status(Status(StatusCode.OK)) |
| 114 | + except Exception as e: |
| 115 | + span.record_exception(e) |
| 116 | + span.set_status(Status(StatusCode.ERROR, str(e))) |
| 117 | + raise |
| 118 | + |
| 119 | + |
| 120 | +@contextmanager |
| 121 | +def trace_sync_context(operation_name: str, attributes: Optional[dict] = None): |
| 122 | + """Sync context manager for adding telemetry span to a code block. |
| 123 | + |
| 124 | + Args: |
| 125 | + operation_name: Name of the operation for the span |
| 126 | + attributes: Optional dictionary of attributes to add to the span |
| 127 | + |
| 128 | + Example: |
| 129 | + with trace_sync_context("blob_upload", {"file_name": file_name}): |
| 130 | + blob_client.upload_blob(data) |
| 131 | + """ |
| 132 | + tracer = get_tracer() |
| 133 | + with tracer.start_as_current_span(operation_name) as span: |
| 134 | + if attributes: |
| 135 | + for key, value in attributes.items(): |
| 136 | + span.set_attribute(key, str(value)) |
| 137 | + |
| 138 | + try: |
| 139 | + yield span |
| 140 | + span.set_status(Status(StatusCode.OK)) |
| 141 | + except Exception as e: |
| 142 | + span.record_exception(e) |
| 143 | + span.set_status(Status(StatusCode.ERROR, str(e))) |
| 144 | + raise |
| 145 | + |
| 146 | + |
| 147 | +def add_span_attributes(attributes: dict): |
| 148 | + """Add attributes to the current span. |
| 149 | + |
| 150 | + Args: |
| 151 | + attributes: Dictionary of attributes to add |
| 152 | + |
| 153 | + Example: |
| 154 | + add_span_attributes({"user_id": user_id, "batch_id": batch_id}) |
| 155 | + """ |
| 156 | + span = trace.get_current_span() |
| 157 | + if span and span.is_recording(): |
| 158 | + for key, value in attributes.items(): |
| 159 | + span.set_attribute(key, str(value)) |
| 160 | + |
| 161 | + |
| 162 | +import asyncio |
0 commit comments