|
| 1 | +# until this is merged: |
| 2 | +# https://github.com/digma-ai/opentelemetry-instrumentation-digma/pull/41 |
| 3 | + |
| 4 | +# stdlib |
| 5 | +import asyncio |
| 6 | +from functools import wraps |
| 7 | +import inspect |
| 8 | +from typing import Callable |
| 9 | +from typing import Dict |
| 10 | + |
| 11 | +# third party |
| 12 | +from opentelemetry import trace |
| 13 | +from opentelemetry.semconv.trace import SpanAttributes |
| 14 | +from opentelemetry.trace import Tracer |
| 15 | + |
| 16 | + |
| 17 | +class TracingDecoratorOptions: |
| 18 | + class NamingSchemes: |
| 19 | + @staticmethod |
| 20 | + def function_qualified_name(func: Callable): |
| 21 | + return func.__qualname__ |
| 22 | + |
| 23 | + default_scheme = function_qualified_name |
| 24 | + |
| 25 | + naming_scheme: Callable[[Callable], str] = NamingSchemes.default_scheme |
| 26 | + default_attributes: Dict[str, str] = {} |
| 27 | + |
| 28 | + @staticmethod |
| 29 | + def set_naming_scheme(naming_scheme: Callable[[Callable], str]): |
| 30 | + TracingDecoratorOptions.naming_scheme = naming_scheme |
| 31 | + |
| 32 | + @staticmethod |
| 33 | + def set_default_attributes(attributes: Dict[str, str] = None): |
| 34 | + for att in attributes: |
| 35 | + TracingDecoratorOptions.default_attributes[att] = attributes[att] |
| 36 | + |
| 37 | + |
| 38 | +def instrument( |
| 39 | + _func_or_class=None, |
| 40 | + *, |
| 41 | + span_name: str = "", |
| 42 | + record_exception: bool = True, |
| 43 | + attributes: Dict[str, str] = None, |
| 44 | + existing_tracer: Tracer = None, |
| 45 | + ignore=False |
| 46 | +): |
| 47 | + """ |
| 48 | + A decorator to instrument a class or function with an OTEL tracing span. |
| 49 | + :param cls: internal, used to specify scope of instrumentation |
| 50 | + :param _func_or_class: The function or span to instrument, this is automatically assigned |
| 51 | + :param span_name: Specify the span name explicitly, rather than use the naming convention. |
| 52 | + This parameter has no effect for class decorators: str |
| 53 | + :param record_exception: Sets whether any exceptions occurring in the span and the stacktrace are recorded |
| 54 | + automatically: bool |
| 55 | + :param attributes:A dictionary of span attributes. These will be automatically added to the span. If defined on a |
| 56 | + class decorator, they will be added to every function span under the class.: dict |
| 57 | + :param existing_tracer: Use a specific tracer instead of creating one :Tracer |
| 58 | + :param ignore: Do not instrument this function, has no effect for class decorators:bool |
| 59 | + :return:The decorator function |
| 60 | + """ |
| 61 | + |
| 62 | + def decorate_class(cls): |
| 63 | + for name, method in inspect.getmembers(cls, inspect.isfunction): |
| 64 | + # Ignore private functions, TODO: maybe make this a setting? |
| 65 | + if not name.startswith("_"): |
| 66 | + |
| 67 | + if isinstance(inspect.getattr_static(cls, name), staticmethod): |
| 68 | + setattr( |
| 69 | + cls, |
| 70 | + name, |
| 71 | + staticmethod( |
| 72 | + instrument( |
| 73 | + record_exception=record_exception, |
| 74 | + attributes=attributes, |
| 75 | + existing_tracer=existing_tracer, |
| 76 | + )(method) |
| 77 | + ), |
| 78 | + ) |
| 79 | + else: |
| 80 | + setattr( |
| 81 | + cls, |
| 82 | + name, |
| 83 | + instrument( |
| 84 | + record_exception=record_exception, |
| 85 | + attributes=attributes, |
| 86 | + existing_tracer=existing_tracer, |
| 87 | + )(method), |
| 88 | + ) |
| 89 | + |
| 90 | + return cls |
| 91 | + |
| 92 | + # Check if this is a span or class decorator |
| 93 | + if inspect.isclass(_func_or_class): |
| 94 | + return decorate_class(_func_or_class) |
| 95 | + |
| 96 | + def span_decorator(func_or_class): |
| 97 | + |
| 98 | + if inspect.isclass(func_or_class): |
| 99 | + return decorate_class(func_or_class) |
| 100 | + |
| 101 | + # sig = inspect.signature(func_or_class) |
| 102 | + |
| 103 | + # Check if already decorated (happens if both class and function |
| 104 | + # decorated). If so, we keep the function decorator settings only |
| 105 | + undecorated_func = getattr(func_or_class, "__tracing_unwrapped__", None) |
| 106 | + if undecorated_func: |
| 107 | + # We have already decorated this function, override |
| 108 | + return func_or_class |
| 109 | + |
| 110 | + setattr(func_or_class, "__tracing_unwrapped__", func_or_class) |
| 111 | + |
| 112 | + tracer = existing_tracer or trace.get_tracer(func_or_class.__module__) |
| 113 | + |
| 114 | + def _set_semantic_attributes(span, func: Callable): |
| 115 | + span.set_attribute(SpanAttributes.CODE_NAMESPACE, func.__module__) |
| 116 | + span.set_attribute(SpanAttributes.CODE_FUNCTION, func.__qualname__) |
| 117 | + span.set_attribute(SpanAttributes.CODE_FILEPATH, func.__code__.co_filename) |
| 118 | + span.set_attribute(SpanAttributes.CODE_LINENO, func.__code__.co_firstlineno) |
| 119 | + |
| 120 | + def _set_attributes(span, attributes_dict): |
| 121 | + if attributes_dict: |
| 122 | + for att in attributes_dict: |
| 123 | + span.set_attribute(att, attributes_dict[att]) |
| 124 | + |
| 125 | + @wraps(func_or_class) |
| 126 | + def wrap_with_span_sync(*args, **kwargs): |
| 127 | + name = span_name or TracingDecoratorOptions.naming_scheme(func_or_class) |
| 128 | + with tracer.start_as_current_span( |
| 129 | + name, record_exception=record_exception |
| 130 | + ) as span: |
| 131 | + _set_semantic_attributes(span, func_or_class) |
| 132 | + _set_attributes(span, TracingDecoratorOptions.default_attributes) |
| 133 | + _set_attributes(span, attributes) |
| 134 | + return func_or_class(*args, **kwargs) |
| 135 | + |
| 136 | + @wraps(func_or_class) |
| 137 | + async def wrap_with_span_async(*args, **kwargs): |
| 138 | + name = span_name or TracingDecoratorOptions.naming_scheme(func_or_class) |
| 139 | + with tracer.start_as_current_span( |
| 140 | + name, record_exception=record_exception |
| 141 | + ) as span: |
| 142 | + _set_semantic_attributes(span, func_or_class) |
| 143 | + _set_attributes(span, TracingDecoratorOptions.default_attributes) |
| 144 | + _set_attributes(span, attributes) |
| 145 | + return await func_or_class(*args, **kwargs) |
| 146 | + |
| 147 | + if ignore: |
| 148 | + return func_or_class |
| 149 | + |
| 150 | + wrapper = ( |
| 151 | + wrap_with_span_async |
| 152 | + if asyncio.iscoroutinefunction(func_or_class) |
| 153 | + else wrap_with_span_sync |
| 154 | + ) |
| 155 | + wrapper.__signature__ = inspect.signature(func_or_class) |
| 156 | + |
| 157 | + return wrapper |
| 158 | + |
| 159 | + if _func_or_class is None: |
| 160 | + return span_decorator |
| 161 | + else: |
| 162 | + return span_decorator(_func_or_class) |
0 commit comments