Skip to content

Commit

Permalink
Capture Sentry event IDs for server errors (#20)
Browse files Browse the repository at this point in the history
* Capture last Sentry event ID for server errors

* Wait for Sentry event ID

* Support Flask and Django

* Update some dev deps

* Fix

* Check if Sentry was initialized
  • Loading branch information
itssimon authored Jun 9, 2024
1 parent 70f0663 commit 934389c
Show file tree
Hide file tree
Showing 5 changed files with 1,134 additions and 528 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ jobs:
if: steps.cached-poetry.outputs.cache-hit != 'true'
uses: snok/install-poetry@v1
with:
version: "1.6.1"
version: "1.8.3"
virtualenvs-in-project: true
- uses: actions/setup-python@v5
with:
python-version: "3.11"
python-version: "3.12"
cache: poetry
- name: Run Poetry check
run: poetry check
Expand Down Expand Up @@ -82,7 +82,7 @@ jobs:
if: steps.cached-poetry.outputs.cache-hit != 'true'
uses: snok/install-poetry@v1
with:
version: "1.6.1"
version: "1.8.3"
virtualenvs-in-project: true
- name: Build Python package wheel
run: poetry build -f wheel
Expand Down
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
default_language_version:
python: "3.11"
python: "3.12"
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
Expand All @@ -8,13 +8,13 @@ repos:
- id: trailing-whitespace
- id: mixed-line-ending
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.1.3
rev: v0.4.8
hooks:
- id: ruff
args: ["--fix", "--exit-non-zero-on-fix"]
- id: ruff-format
- repo: https://github.com/python-poetry/poetry
rev: "1.6.1"
rev: "1.8.3"
hooks:
- id: poetry-check
- id: poetry-lock
Expand Down
34 changes: 34 additions & 0 deletions apitally/client/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
import contextlib
import os
import re
Expand Down Expand Up @@ -243,6 +244,7 @@ class ServerError:
class ServerErrorCounter:
def __init__(self) -> None:
self.error_counts: Counter[ServerError] = Counter()
self.sentry_event_ids: Dict[ServerError, str] = {}
self._lock = threading.Lock()

def add_server_error(self, consumer: Optional[str], method: str, path: str, exception: BaseException) -> None:
Expand All @@ -259,6 +261,36 @@ def add_server_error(self, consumer: Optional[str], method: str, path: str, exce
traceback=self._get_truncated_exception_traceback(exception),
)
self.error_counts[server_error] += 1
self.capture_sentry_event_id(server_error)

def capture_sentry_event_id(self, server_error: ServerError) -> None:
try:
from sentry_sdk.hub import Hub
from sentry_sdk.scope import Scope
except ImportError:
return # pragma: no cover
if not hasattr(Scope, "get_isolation_scope") or not hasattr(Scope, "last_event_id"):
# sentry-sdk < 2.2.0 is not supported
return # pragma: no cover
if Hub.current.client is None:
return # sentry-sdk not initialized

scope = Scope.get_isolation_scope()
if event_id := scope.last_event_id():
self.sentry_event_ids[server_error] = event_id
return

async def _wait_for_sentry_event_id(scope: Scope) -> None:
i = 0
while not (event_id := scope.last_event_id()) and i < 100:
i += 1
await asyncio.sleep(0.001)
if event_id:
self.sentry_event_ids[server_error] = event_id

with contextlib.suppress(RuntimeError): # ignore no running loop
loop = asyncio.get_running_loop()
loop.create_task(_wait_for_sentry_event_id(scope))

def get_and_reset_server_errors(self) -> List[Dict[str, Any]]:
data: List[Dict[str, Any]] = []
Expand All @@ -272,10 +304,12 @@ def get_and_reset_server_errors(self) -> List[Dict[str, Any]]:
"type": server_error.type,
"msg": server_error.msg,
"traceback": server_error.traceback,
"sentry_event_id": self.sentry_event_ids.get(server_error),
"error_count": count,
}
)
self.error_counts.clear()
self.sentry_event_ids.clear()
return data

@staticmethod
Expand Down
Loading

0 comments on commit 934389c

Please sign in to comment.