Skip to content

Commit

Permalink
Record exception on context manager exit
Browse files Browse the repository at this point in the history
This updates the tracer context manager to automatically record
exceptions as events on exit if an exception was raised within the
context manager's context.
  • Loading branch information
owais committed Sep 25, 2020
1 parent c1ec444 commit fc94cd4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,7 @@ def use_span(
context_api.detach(token)

except Exception as error: # pylint: disable=broad-except
span.record_exception(error)
if (
isinstance(span, Span)
and span.status is None
Expand Down
18 changes: 18 additions & 0 deletions opentelemetry-sdk/tests/trace/test_trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,24 @@ def test_record_exception(self):
exception_event.attributes["exception.stacktrace"],
)

def test_record_exception_context_manager(self):
try:
with self.tracer.start_as_current_span("span") as span:
raise RuntimeError("example error")
except RuntimeError:
pass
finally:
self.assertEqual(len(span.events), 1)
event = span.events[0]
self.assertEqual("exception", event.name)
self.assertEqual("RuntimeError", event.attributes["exception.type"])
self.assertEqual("example error", event.attributes["exception.message"])

stacktrace = '''in test_record_exception_context_manager
raise RuntimeError("example error")
RuntimeError: example error'''
self.assertIn(stacktrace, event.attributes["exception.stacktrace"])


def span_event_start_fmt(span_processor_name, span_name):
return span_processor_name + ":" + span_name + ":start"
Expand Down

0 comments on commit fc94cd4

Please sign in to comment.