ldobserve.observe

  1import contextlib
  2import logging
  3import typing
  4from opentelemetry.context import Context
  5from opentelemetry.instrumentation.logging import LEVELS
  6from opentelemetry.sdk._logs import LoggingHandler
  7from opentelemetry.trace import Span, Tracer
  8import opentelemetry.trace as trace
  9from opentelemetry.util.types import Attributes, AttributeValue
 10from opentelemetry._logs import get_logger_provider
 11from ldobserve._otel.configuration import _OTELConfiguration
 12from ldobserve._otel.global_attributes import (
 13    merge_global_attributes,
 14    remove_global_attributes,
 15    set_global_attributes,
 16)
 17from ldobserve._source_context import exception_attributes
 18from ldobserve._util.dict import flatten_dict
 19
 20from opentelemetry.metrics import (
 21    _Gauge as APIGauge,
 22    Histogram as APIHistogram,
 23    Counter as APICounter,
 24    UpDownCounter as APIUpDownCounter,
 25)
 26
 27_NAME = "launchdarkly-observability"
 28_ERROR_NAME = "launchdarkly.error"
 29
 30
 31class _ObserveInstance:
 32    _project_id: str
 33    _tracer: Tracer
 34
 35    _provider = get_logger_provider()
 36    _logger = logging.getLogger(__name__)
 37    _otel_configuration: _OTELConfiguration
 38
 39    _gauges: dict[str, APIGauge] = dict()
 40    _counters: dict[str, APICounter] = dict()
 41    _histograms: dict[str, APIHistogram] = dict()
 42    _up_down_counters: dict[str, APIUpDownCounter] = dict()
 43
 44    @property
 45    def log_handler(self) -> logging.Handler:
 46        return self._otel_configuration.log_handler
 47
 48    def __init__(self, project_id: str, otel_configuration: _OTELConfiguration):
 49        self._otel_configuration = otel_configuration
 50
 51        # Logger that will only log to OpenTelemetry.
 52        self._logger.propagate = False
 53        self._logger.addHandler(otel_configuration.log_handler)
 54        self._project_id = project_id
 55        self._tracer = otel_configuration.tracer
 56
 57    def record_exception(
 58        self, error: Exception, attributes: typing.Optional[Attributes] = None
 59    ):
 60        if error is None:
 61            return  # Nothing to record
 62
 63        span = trace.get_current_span()
 64        ctx = contextlib.nullcontext(span)
 65        if not span or not span.is_recording():
 66            ctx = self.start_span(_ERROR_NAME)
 67
 68        with ctx as span:
 69            # Source context first, so caller-supplied attributes win on conflict.
 70            attrs = exception_attributes(error)
 71            if attributes:
 72                addedAttributes = flatten_dict(attributes, sep=".")
 73                attrs.update(addedAttributes)
 74
 75            span.record_exception(error, attrs)
 76
 77    def record_metric(
 78        self, name: str, value: float, attributes: typing.Optional[Attributes] = None
 79    ):
 80        if name not in self._gauges:
 81            self._gauges[name] = self._otel_configuration.meter.create_gauge(name)
 82        self._gauges[name].set(value, attributes=merge_global_attributes(attributes))
 83
 84    def record_count(
 85        self, name: str, value: int, attributes: typing.Optional[Attributes] = None
 86    ):
 87        if name not in self._counters:
 88            self._counters[name] = self._otel_configuration.meter.create_counter(name)
 89        self._counters[name].add(value, attributes=merge_global_attributes(attributes))
 90
 91    def record_incr(self, name: str, attributes: typing.Optional[Attributes] = None):
 92        return self.record_count(name, 1, attributes)
 93
 94    def record_histogram(
 95        self, name: str, value: float, attributes: typing.Optional[Attributes] = None
 96    ):
 97        if name not in self._histograms:
 98            self._histograms[name] = self._otel_configuration.meter.create_histogram(
 99                name
100            )
101        self._histograms[name].record(
102            value, attributes=merge_global_attributes(attributes)
103        )
104
105    def record_up_down_counter(
106        self, name: str, value: int, attributes: typing.Optional[Attributes] = None
107    ):
108        if name not in self._up_down_counters:
109            self._up_down_counters[name] = (
110                self._otel_configuration.meter.create_up_down_counter(name)
111            )
112        self._up_down_counters[name].add(
113            value, attributes=merge_global_attributes(attributes)
114        )
115
116    def log(
117        self, message: str, level: int, attributes: typing.Optional[Attributes] = None
118    ):
119        self._logger.log(level, message, extra=attributes)
120
121    @contextlib.contextmanager
122    def start_span(
123        self,
124        name: str,
125        attributes: Attributes = None,
126        record_exception: bool = True,
127        set_status_on_exception: bool = True,
128    ) -> typing.Iterator["Span"]:
129        """
130        Context manager for creating a new span and setting it as the current span.
131
132        Exiting the context manager will call the span's end method,
133        as well as return the current span to its previous value by
134        returning to the previous context.
135
136        Args:
137            name: The name of the span.
138            attributes: The attributes of the span.
139            record_exception: Whether to record any exceptions raised within the
140                context as error event on the span.
141            set_status_on_exception: Only relevant if the returned span is used
142                in a with/context manager. Defines whether the span status will
143
144        Yields:
145            The newly-created span.
146        """
147        with self._tracer.start_as_current_span(
148            name,
149            attributes=attributes,
150            record_exception=record_exception,
151            set_status_on_exception=set_status_on_exception,
152        ) as span:
153            yield span
154
155
156_instance: typing.Optional[_ObserveInstance] = None
157
158
159def _use_instance(func):
160    """Helper function to delegate calls to the instance if it exists."""
161    if not _instance:
162        logging.getLogger(__name__).warning(
163            "The observability singleton was used before it was initialized."
164        )
165        return
166    return func(_instance)
167
168
169def record_exception(error: Exception, attributes: typing.Optional[Attributes] = None):
170    """
171    Record arbitrary exceptions raised within your app.
172
173    Example:
174        import ldobserve.observe as observe
175        # Observability plugin must be initialized.
176
177        def my_fn():
178            try:
179                for i in range(20):
180                    result = 100 / (10 - i)
181                    print(f'dangerous: {result}')
182            except Exception as e:
183                observe.record_exception(e)
184
185
186    :param e: the exception to record. the contents and stacktrace will be recorded.
187    :param attributes: additional metadata to attribute to this error.
188    :return: None
189    """
190    _use_instance(lambda instance: instance.record_exception(error, attributes))
191
192
193def record_metric(
194    name: str, value: float, attributes: typing.Optional[Attributes] = None
195):
196    """
197    Record arbitrary metric values via as a Gauge.
198    A Gauge records any point-in-time measurement, such as the current CPU utilization %.
199    Values with the same metric name and attributes are aggregated via the OTel SDK.
200    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
201    :param name: the name of the metric.
202    :param value: the float value of the metric.
203    :param attributes: additional metadata which can be used to filter and group values.
204    :return: None
205    """
206    _use_instance(lambda instance: instance.record_metric(name, value, attributes))
207
208
209def record_count(name: str, value: int, attributes: typing.Optional[Attributes] = None):
210    """
211    Record arbitrary metric values via as a Counter.
212    A Counter efficiently records an increment in a metric, such as number of cache hits.
213    Values with the same metric name and attributes are aggregated via the OTel SDK.
214    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
215    :param name: the name of the metric.
216    :param value: the float value of the metric.
217    :param attributes: additional metadata which can be used to filter and group values.
218    :return: None
219    """
220    _use_instance(lambda instance: instance.record_count(name, value, attributes))
221
222
223def record_incr(name: str, attributes: typing.Optional[Attributes] = None):
224    """
225    Record arbitrary metric +1 increment via as a Counter.
226    A Counter efficiently records an increment in a metric, such as number of cache hits.
227    Values with the same metric name and attributes are aggregated via the OTel SDK.
228    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
229    :param name: the name of the metric.
230    :param attributes: additional metadata which can be used to filter and group values.
231    :return: None
232    """
233    _use_instance(lambda instance: instance.record_incr(name, attributes))
234
235
236def record_histogram(
237    name: str, value: float, attributes: typing.Optional[Attributes] = None
238):
239    """
240    Record arbitrary metric values via as a Histogram.
241    A Histogram efficiently records near-by point-in-time measurement into a bucketed aggregate.
242    Values with the same metric name and attributes are aggregated via the OTel SDK.
243    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
244    :param name: the name of the metric.
245    :param value: the float value of the metric.
246    :param attributes: additional metadata which can be used to filter and group values.
247    :return: None
248    """
249    _use_instance(lambda instance: instance.record_histogram(name, value, attributes))
250
251
252def record_up_down_counter(
253    name: str, value: int, attributes: typing.Optional[Attributes] = None
254):
255    """
256    Record arbitrary metric values via as a UpDownCounter.
257    A UpDownCounter efficiently records an increment or decrement in a metric, such as number of paying customers.
258    Values with the same metric name and attributes are aggregated via the OTel SDK.
259    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
260    :param name: the name of the metric.
261    :param value: the float value of the metric.
262    :param attributes: additional metadata which can be used to filter and group values.
263    :return: None
264    """
265    _use_instance(
266        lambda instance: instance.record_up_down_counter(name, value, attributes)
267    )
268
269
270def record_log(
271    message: str,
272    level: int,
273    attributes: typing.Optional[Attributes] = None,
274):
275    """
276    Records a log. This log will be recorded to LaunchDarkly, but will not be send to other log handlers.
277    A Log records a message with a level and optional attributes.
278    :param message: the message to record.
279    :param level: the level of the log.
280    :param attributes: additional metadata which can be used to filter and group values.
281    :return: None
282    """
283    _use_instance(lambda instance: instance.log(message, level, attributes))
284
285
286def set_attributes(attributes: typing.Mapping[str, AttributeValue]) -> None:
287    """
288    Set global attributes that are added to every span, log record, and metric data point
289    recorded after this call. Attributes are merged by key into the existing global attributes.
290
291    Attributes provided on an individual span, log, or metric take precedence over global
292    attributes, and global attributes take precedence over resource attributes. A span uses the
293    global attributes that are set when it starts.
294
295    Global attributes are kept in memory for the lifetime of the process and are shared by all
296    threads. They may be set before the observability plugin is initialized.
297
298    Example:
299        import ldobserve.observe as observe
300
301        observe.set_attributes({"tenant.id": "acme", "deployment.region": "us-east-1"})
302
303    :param attributes: the attributes to set. Values must be valid OpenTelemetry attribute values;
304        invalid values are ignored.
305    :return: None
306    """
307    set_global_attributes(attributes)
308
309
310def remove_attributes(keys: typing.Iterable[str]) -> None:
311    """
312    Remove global attributes previously set with :func:`set_attributes`.
313
314    Example:
315        import ldobserve.observe as observe
316
317        observe.remove_attributes(["tenant.id"])
318
319    :param keys: the keys of the global attributes to remove. Unknown keys are ignored.
320    :return: None
321    """
322    remove_global_attributes(keys)
323
324
325def logging_handler() -> logging.Handler:
326    """A logging handler implementing `logging.Handler` that allows plugging LaunchDarkly Observability
327    into your existing logging setup. Standard logging will be automatically instrumented unless
328    :class:`ObservabilityConfig.instrument_logging <ldobserve.config.ObservabilityConfig.instrument_logging>` is set to False.
329
330    Example:
331        import ldobserve.observe as observe
332        from loguru import logger
333
334        # Observability plugin must be initialized.
335        # If the Observability plugin is not initialized, then a NullHandler will be returned.
336
337        logger.add(
338            observe.logging_handler(),
339            format="{message}",
340            level="INFO",
341            backtrace=True,
342        )
343    """
344    if not _instance:
345        return logging.NullHandler()
346    return _instance.log_handler
347
348
349@contextlib.contextmanager
350def start_span(
351    name: str,
352    attributes: Attributes = None,
353    record_exception: bool = True,
354    set_status_on_exception: bool = True,
355) -> typing.Iterator["Span"]:
356    """
357    Context manager for creating a new span and setting it as the current span.
358
359    Exiting the context manager will call the span's end method,
360    as well as return the current span to its previous value by
361    returning to the previous context.
362
363    Args:
364        name: The name of the span.
365        attributes: The attributes of the span.
366        record_exception: Whether to record any exceptions raised within the
367            context as error event on the span.
368        set_status_on_exception: Only relevant if the returned span is used
369            in a with/context manager. Defines whether the span status will
370
371    Yields:
372        The newly-created span.
373    """
374    if _instance:
375        with _instance.start_span(
376            name,
377            attributes=attributes,
378            record_exception=record_exception,
379            set_status_on_exception=set_status_on_exception,
380        ) as span:
381            yield span
382    else:
383        # If not initialized, then get a tracer and use it to create a span.
384        # We don't want to prevent user code from executing correctly if
385        # the plugin is not initialized.
386        logging.getLogger(__name__).warning(
387            "The observability singleton was used before it was initialized."
388        )
389        with trace.get_tracer(__name__).start_as_current_span(
390            name,
391            attributes=attributes,
392            record_exception=record_exception,
393            set_status_on_exception=set_status_on_exception,
394        ) as span:
395            yield span
396
397
398def is_initialized() -> bool:
399    return _instance != None
def record_exception( error: Exception, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None):
170def record_exception(error: Exception, attributes: typing.Optional[Attributes] = None):
171    """
172    Record arbitrary exceptions raised within your app.
173
174    Example:
175        import ldobserve.observe as observe
176        # Observability plugin must be initialized.
177
178        def my_fn():
179            try:
180                for i in range(20):
181                    result = 100 / (10 - i)
182                    print(f'dangerous: {result}')
183            except Exception as e:
184                observe.record_exception(e)
185
186
187    :param e: the exception to record. the contents and stacktrace will be recorded.
188    :param attributes: additional metadata to attribute to this error.
189    :return: None
190    """
191    _use_instance(lambda instance: instance.record_exception(error, attributes))

Record arbitrary exceptions raised within your app.

Example: import ldobserve.observe as observe # Observability plugin must be initialized.

def my_fn():
    try:
        for i in range(20):
            result = 100 / (10 - i)
            print(f'dangerous: {result}')
    except Exception as e:
        observe.record_exception(e)
Parameters
  • e: the exception to record. the contents and stacktrace will be recorded.
  • attributes: additional metadata to attribute to this error.
Returns

None

def record_metric( name: str, value: float, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None):
194def record_metric(
195    name: str, value: float, attributes: typing.Optional[Attributes] = None
196):
197    """
198    Record arbitrary metric values via as a Gauge.
199    A Gauge records any point-in-time measurement, such as the current CPU utilization %.
200    Values with the same metric name and attributes are aggregated via the OTel SDK.
201    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
202    :param name: the name of the metric.
203    :param value: the float value of the metric.
204    :param attributes: additional metadata which can be used to filter and group values.
205    :return: None
206    """
207    _use_instance(lambda instance: instance.record_metric(name, value, attributes))

Record arbitrary metric values via as a Gauge. A Gauge records any point-in-time measurement, such as the current CPU utilization %. Values with the same metric name and attributes are aggregated via the OTel SDK. See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.

Parameters
  • name: the name of the metric.
  • value: the float value of the metric.
  • attributes: additional metadata which can be used to filter and group values.
Returns

None

def record_count( name: str, value: int, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None):
210def record_count(name: str, value: int, attributes: typing.Optional[Attributes] = None):
211    """
212    Record arbitrary metric values via as a Counter.
213    A Counter efficiently records an increment in a metric, such as number of cache hits.
214    Values with the same metric name and attributes are aggregated via the OTel SDK.
215    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
216    :param name: the name of the metric.
217    :param value: the float value of the metric.
218    :param attributes: additional metadata which can be used to filter and group values.
219    :return: None
220    """
221    _use_instance(lambda instance: instance.record_count(name, value, attributes))

Record arbitrary metric values via as a Counter. A Counter efficiently records an increment in a metric, such as number of cache hits. Values with the same metric name and attributes are aggregated via the OTel SDK. See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.

Parameters
  • name: the name of the metric.
  • value: the float value of the metric.
  • attributes: additional metadata which can be used to filter and group values.
Returns

None

def record_incr( name: str, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None):
224def record_incr(name: str, attributes: typing.Optional[Attributes] = None):
225    """
226    Record arbitrary metric +1 increment via as a Counter.
227    A Counter efficiently records an increment in a metric, such as number of cache hits.
228    Values with the same metric name and attributes are aggregated via the OTel SDK.
229    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
230    :param name: the name of the metric.
231    :param attributes: additional metadata which can be used to filter and group values.
232    :return: None
233    """
234    _use_instance(lambda instance: instance.record_incr(name, attributes))

Record arbitrary metric +1 increment via as a Counter. A Counter efficiently records an increment in a metric, such as number of cache hits. Values with the same metric name and attributes are aggregated via the OTel SDK. See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.

Parameters
  • name: the name of the metric.
  • attributes: additional metadata which can be used to filter and group values.
Returns

None

def record_histogram( name: str, value: float, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None):
237def record_histogram(
238    name: str, value: float, attributes: typing.Optional[Attributes] = None
239):
240    """
241    Record arbitrary metric values via as a Histogram.
242    A Histogram efficiently records near-by point-in-time measurement into a bucketed aggregate.
243    Values with the same metric name and attributes are aggregated via the OTel SDK.
244    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
245    :param name: the name of the metric.
246    :param value: the float value of the metric.
247    :param attributes: additional metadata which can be used to filter and group values.
248    :return: None
249    """
250    _use_instance(lambda instance: instance.record_histogram(name, value, attributes))

Record arbitrary metric values via as a Histogram. A Histogram efficiently records near-by point-in-time measurement into a bucketed aggregate. Values with the same metric name and attributes are aggregated via the OTel SDK. See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.

Parameters
  • name: the name of the metric.
  • value: the float value of the metric.
  • attributes: additional metadata which can be used to filter and group values.
Returns

None

def record_up_down_counter( name: str, value: int, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None):
253def record_up_down_counter(
254    name: str, value: int, attributes: typing.Optional[Attributes] = None
255):
256    """
257    Record arbitrary metric values via as a UpDownCounter.
258    A UpDownCounter efficiently records an increment or decrement in a metric, such as number of paying customers.
259    Values with the same metric name and attributes are aggregated via the OTel SDK.
260    See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.
261    :param name: the name of the metric.
262    :param value: the float value of the metric.
263    :param attributes: additional metadata which can be used to filter and group values.
264    :return: None
265    """
266    _use_instance(
267        lambda instance: instance.record_up_down_counter(name, value, attributes)
268    )

Record arbitrary metric values via as a UpDownCounter. A UpDownCounter efficiently records an increment or decrement in a metric, such as number of paying customers. Values with the same metric name and attributes are aggregated via the OTel SDK. See https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for more details.

Parameters
  • name: the name of the metric.
  • value: the float value of the metric.
  • attributes: additional metadata which can be used to filter and group values.
Returns

None

def record_log( message: str, level: int, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None):
271def record_log(
272    message: str,
273    level: int,
274    attributes: typing.Optional[Attributes] = None,
275):
276    """
277    Records a log. This log will be recorded to LaunchDarkly, but will not be send to other log handlers.
278    A Log records a message with a level and optional attributes.
279    :param message: the message to record.
280    :param level: the level of the log.
281    :param attributes: additional metadata which can be used to filter and group values.
282    :return: None
283    """
284    _use_instance(lambda instance: instance.log(message, level, attributes))

Records a log. This log will be recorded to LaunchDarkly, but will not be send to other log handlers. A Log records a message with a level and optional attributes.

Parameters
  • message: the message to record.
  • level: the level of the log.
  • attributes: additional metadata which can be used to filter and group values.
Returns

None

def set_attributes( attributes: Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]) -> None:
287def set_attributes(attributes: typing.Mapping[str, AttributeValue]) -> None:
288    """
289    Set global attributes that are added to every span, log record, and metric data point
290    recorded after this call. Attributes are merged by key into the existing global attributes.
291
292    Attributes provided on an individual span, log, or metric take precedence over global
293    attributes, and global attributes take precedence over resource attributes. A span uses the
294    global attributes that are set when it starts.
295
296    Global attributes are kept in memory for the lifetime of the process and are shared by all
297    threads. They may be set before the observability plugin is initialized.
298
299    Example:
300        import ldobserve.observe as observe
301
302        observe.set_attributes({"tenant.id": "acme", "deployment.region": "us-east-1"})
303
304    :param attributes: the attributes to set. Values must be valid OpenTelemetry attribute values;
305        invalid values are ignored.
306    :return: None
307    """
308    set_global_attributes(attributes)

Set global attributes that are added to every span, log record, and metric data point recorded after this call. Attributes are merged by key into the existing global attributes.

Attributes provided on an individual span, log, or metric take precedence over global attributes, and global attributes take precedence over resource attributes. A span uses the global attributes that are set when it starts.

Global attributes are kept in memory for the lifetime of the process and are shared by all threads. They may be set before the observability plugin is initialized.

Example: import ldobserve.observe as observe

observe.set_attributes({"tenant.id": "acme", "deployment.region": "us-east-1"})
Parameters
  • attributes: the attributes to set. Values must be valid OpenTelemetry attribute values; invalid values are ignored.
Returns

None

def remove_attributes(keys: Iterable[str]) -> None:
311def remove_attributes(keys: typing.Iterable[str]) -> None:
312    """
313    Remove global attributes previously set with :func:`set_attributes`.
314
315    Example:
316        import ldobserve.observe as observe
317
318        observe.remove_attributes(["tenant.id"])
319
320    :param keys: the keys of the global attributes to remove. Unknown keys are ignored.
321    :return: None
322    """
323    remove_global_attributes(keys)

Remove global attributes previously set with set_attributes().

Example: import ldobserve.observe as observe

observe.remove_attributes(["tenant.id"])
Parameters
  • keys: the keys of the global attributes to remove. Unknown keys are ignored.
Returns

None

def logging_handler() -> logging.Handler:
326def logging_handler() -> logging.Handler:
327    """A logging handler implementing `logging.Handler` that allows plugging LaunchDarkly Observability
328    into your existing logging setup. Standard logging will be automatically instrumented unless
329    :class:`ObservabilityConfig.instrument_logging <ldobserve.config.ObservabilityConfig.instrument_logging>` is set to False.
330
331    Example:
332        import ldobserve.observe as observe
333        from loguru import logger
334
335        # Observability plugin must be initialized.
336        # If the Observability plugin is not initialized, then a NullHandler will be returned.
337
338        logger.add(
339            observe.logging_handler(),
340            format="{message}",
341            level="INFO",
342            backtrace=True,
343        )
344    """
345    if not _instance:
346        return logging.NullHandler()
347    return _instance.log_handler

A logging handler implementing logging.Handler that allows plugging LaunchDarkly Observability into your existing logging setup. Standard logging will be automatically instrumented unless ObservabilityConfig.instrument_logging <ldobserve.config.ObservabilityConfig.instrument_logging> is set to False.

Example: import ldobserve.observe as observe from loguru import logger

# Observability plugin must be initialized.
# If the Observability plugin is not initialized, then a NullHandler will be returned.

logger.add(
    observe.logging_handler(),
    format="{message}",
    level="INFO",
    backtrace=True,
)
@contextlib.contextmanager
def start_span( name: str, attributes: Optional[Mapping[str, Union[str, bool, int, float, Sequence[str], Sequence[bool], Sequence[int], Sequence[float]]]] = None, record_exception: bool = True, set_status_on_exception: bool = True) -> Iterator[opentelemetry.trace.span.Span]:
350@contextlib.contextmanager
351def start_span(
352    name: str,
353    attributes: Attributes = None,
354    record_exception: bool = True,
355    set_status_on_exception: bool = True,
356) -> typing.Iterator["Span"]:
357    """
358    Context manager for creating a new span and setting it as the current span.
359
360    Exiting the context manager will call the span's end method,
361    as well as return the current span to its previous value by
362    returning to the previous context.
363
364    Args:
365        name: The name of the span.
366        attributes: The attributes of the span.
367        record_exception: Whether to record any exceptions raised within the
368            context as error event on the span.
369        set_status_on_exception: Only relevant if the returned span is used
370            in a with/context manager. Defines whether the span status will
371
372    Yields:
373        The newly-created span.
374    """
375    if _instance:
376        with _instance.start_span(
377            name,
378            attributes=attributes,
379            record_exception=record_exception,
380            set_status_on_exception=set_status_on_exception,
381        ) as span:
382            yield span
383    else:
384        # If not initialized, then get a tracer and use it to create a span.
385        # We don't want to prevent user code from executing correctly if
386        # the plugin is not initialized.
387        logging.getLogger(__name__).warning(
388            "The observability singleton was used before it was initialized."
389        )
390        with trace.get_tracer(__name__).start_as_current_span(
391            name,
392            attributes=attributes,
393            record_exception=record_exception,
394            set_status_on_exception=set_status_on_exception,
395        ) as span:
396            yield span

Context manager for creating a new span and setting it as the current span.

Exiting the context manager will call the span's end method, as well as return the current span to its previous value by returning to the previous context.

Args: name: The name of the span. attributes: The attributes of the span. record_exception: Whether to record any exceptions raised within the context as error event on the span. set_status_on_exception: Only relevant if the returned span is used in a with/context manager. Defines whether the span status will

Yields: The newly-created span.

def is_initialized() -> bool:
399def is_initialized() -> bool:
400    return _instance != None