Skip to content

Span.record_exception doesn't use the exception parameter to format the stacktrace #3762

@alexmojaki

Description

@alexmojaki

This line:

formats a stacktrace for the currently handled exception, which may be different from the exception passed to the method.

Here's an example of how this can go wrong:

from opentelemetry.sdk.trace import TracerProvider

span = TracerProvider().get_tracer(__name__).start_span('')

try:
    raise ValueError('bad')
except ValueError as e:
    # This happens to work correctly because `e` is the currently handled exception.
    span.record_exception(e)
    print(span.events[0].attributes['exception.stacktrace'])
    """
    Traceback (most recent call last):
      File "...", line ..., in <module>
        raise ValueError('bad')
    ValueError: bad
    """

    exc = e

# This doesn't work because there is no longer an exception being currently handled.
span.record_exception(exc)
print(span.events[1].attributes['exception.stacktrace'])
"""
NoneType: None
"""

try:
    raise TypeError('worse')
except TypeError:
    # Recording an old exception means that the type and message don't match the stacktrace.
    span.record_exception(exc)
    print(span.events[2].attributes['exception.type'])
    """
    ValueError
    """
    print(span.events[2].attributes['exception.stacktrace'])
    """
    Traceback (most recent call last):
      File "...", line ..., in <module>
        raise TypeError('worse')
    TypeError: worse
    """

Replacing the faulty line with this works correctly:

stacktrace = ''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions