mirror of
https://github.com/open-telemetry/opentelemetry-python-contrib.git
synced 2025-07-31 14:11:50 +08:00
Record exception on context manager exit (#1162)
This commit is contained in:
@ -50,7 +50,11 @@ from opentelemetry.instrumentation.metric import (
|
||||
from opentelemetry.instrumentation.requests.version import __version__
|
||||
from opentelemetry.instrumentation.utils import http_status_to_canonical_code
|
||||
from opentelemetry.trace import SpanKind, get_tracer
|
||||
from opentelemetry.trace.status import Status, StatusCanonicalCode
|
||||
from opentelemetry.trace.status import (
|
||||
EXCEPTION_STATUS_FIELD,
|
||||
Status,
|
||||
StatusCanonicalCode,
|
||||
)
|
||||
|
||||
# A key to a context variable to avoid creating duplicate spans when instrumenting
|
||||
# both, Session.request and Session.send, since Session.request calls into Session.send
|
||||
@ -121,8 +125,6 @@ def _instrument(tracer_provider=None, span_callback=None):
|
||||
method = method.upper()
|
||||
span_name = "HTTP {}".format(method)
|
||||
|
||||
exception = None
|
||||
|
||||
recorder = RequestsInstrumentor().metric_recorder
|
||||
|
||||
labels = {}
|
||||
@ -132,6 +134,7 @@ def _instrument(tracer_provider=None, span_callback=None):
|
||||
with get_tracer(
|
||||
__name__, __version__, tracer_provider
|
||||
).start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
|
||||
exception = None
|
||||
with recorder.record_duration(labels):
|
||||
if span.is_recording():
|
||||
span.set_attribute("component", "http")
|
||||
@ -150,16 +153,15 @@ def _instrument(tracer_provider=None, span_callback=None):
|
||||
result = call_wrapped() # *** PROCEED
|
||||
except Exception as exc: # pylint: disable=W0703
|
||||
exception = exc
|
||||
setattr(
|
||||
exception,
|
||||
EXCEPTION_STATUS_FIELD,
|
||||
_exception_to_canonical_code(exception),
|
||||
)
|
||||
result = getattr(exc, "response", None)
|
||||
finally:
|
||||
context.detach(token)
|
||||
|
||||
if exception is not None and span.is_recording():
|
||||
span.set_status(
|
||||
Status(_exception_to_canonical_code(exception))
|
||||
)
|
||||
span.record_exception(exception)
|
||||
|
||||
if result is not None:
|
||||
if span.is_recording():
|
||||
span.set_attribute(
|
||||
@ -184,8 +186,8 @@ def _instrument(tracer_provider=None, span_callback=None):
|
||||
if span_callback is not None:
|
||||
span_callback(span, result)
|
||||
|
||||
if exception is not None:
|
||||
raise exception.with_traceback(exception.__traceback__)
|
||||
if exception is not None:
|
||||
raise exception.with_traceback(exception.__traceback__)
|
||||
|
||||
return result
|
||||
|
||||
|
Reference in New Issue
Block a user