Skip to content

Fix breadcrumb sorting #3511

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion sentry_sdk/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
capture_internal_exception,
capture_internal_exceptions,
ContextVar,
datetime_from_isoformat,
disable_capture_event,
event_from_exception,
exc_info_from_error,
Expand Down Expand Up @@ -1307,7 +1308,16 @@ def _apply_breadcrumbs_to_event(self, event, hint, options):
event.setdefault("breadcrumbs", {}).setdefault("values", []).extend(
self._breadcrumbs
)
event["breadcrumbs"]["values"].sort(key=lambda crumb: crumb["timestamp"])

# Attempt to sort timestamps
try:
for crumb in event["breadcrumbs"]["values"]:
if isinstance(crumb["timestamp"], str):
crumb["timestamp"] = datetime_from_isoformat(crumb["timestamp"])

event["breadcrumbs"]["values"].sort(key=lambda crumb: crumb["timestamp"])
except Exception:
pass

def _apply_user_to_event(self, event, hint, options):
# type: (Event, Hint, Optional[Dict[str, Any]]) -> None
Expand Down
9 changes: 9 additions & 0 deletions sentry_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,15 @@ def format_timestamp(value):
return utctime.strftime("%Y-%m-%dT%H:%M:%S.%fZ")


def datetime_from_isoformat(value):
# type: (str) -> datetime
try:
return datetime.fromisoformat(value)
except AttributeError:
# py 3.6
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")


def event_hint_with_exc_info(exc_info=None):
# type: (Optional[ExcInfo]) -> Dict[str, Optional[ExcInfo]]
"""Creates a hint with the exc info filled in."""
Expand Down
31 changes: 31 additions & 0 deletions tests/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,37 @@ def test_breadcrumb_ordering(sentry_init, capture_events):
assert timestamps_from_event == sorted(timestamps)


def test_breadcrumb_ordering_different_types(sentry_init, capture_events):
sentry_init()
events = capture_events()

timestamps = [
datetime.datetime.now() - datetime.timedelta(days=10),
datetime.datetime.now() - datetime.timedelta(days=8),
datetime.datetime.now() - datetime.timedelta(days=12),
]

for i, timestamp in enumerate(timestamps):
add_breadcrumb(
message="Authenticated at %s" % timestamp,
category="auth",
level="info",
timestamp=timestamp if i % 2 == 0 else timestamp.isoformat(),
)

capture_exception(ValueError())
(event,) = events

assert len(event["breadcrumbs"]["values"]) == len(timestamps)
timestamps_from_event = [
datetime.datetime.strptime(
x["timestamp"].replace("Z", ""), "%Y-%m-%dT%H:%M:%S.%f"
)
for x in event["breadcrumbs"]["values"]
]
assert timestamps_from_event == sorted(timestamps)


def test_attachments(sentry_init, capture_envelopes):
sentry_init()
envelopes = capture_envelopes()
Expand Down
Loading