errorgap 0.2.0__tar.gz → 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {errorgap-0.2.0 → errorgap-0.3.0}/CHANGELOG.md +8 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/PKG-INFO +14 -3
- {errorgap-0.2.0 → errorgap-0.3.0}/README.md +13 -2
- {errorgap-0.2.0 → errorgap-0.3.0}/pyproject.toml +1 -1
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/django.py +57 -2
- errorgap-0.3.0/src/errorgap/fastapi.py +120 -0
- errorgap-0.3.0/src/errorgap/version.py +1 -0
- errorgap-0.3.0/tests/test_django.py +111 -0
- errorgap-0.3.0/tests/test_fastapi.py +82 -0
- errorgap-0.2.0/src/errorgap/fastapi.py +0 -67
- errorgap-0.2.0/src/errorgap/version.py +0 -1
- errorgap-0.2.0/tests/test_django.py +0 -65
- errorgap-0.2.0/tests/test_fastapi.py +0 -39
- {errorgap-0.2.0 → errorgap-0.3.0}/.github/workflows/ci.yml +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/.github/workflows/release.yml +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/.gitignore +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/LICENSE +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/__init__.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/apm.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/backtrace.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/client.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/configuration.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/filter.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/flask.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/handlers.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/notice.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/transaction_context.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/src/errorgap/wsgi.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/conftest.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/test_apm.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/test_backtrace.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/test_client.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/test_configuration.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/test_filter.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/test_flask.py +0 -0
- {errorgap-0.2.0 → errorgap-0.3.0}/tests/test_notice.py +0 -0
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 — 2026-10-04
|
|
4
|
+
|
|
5
|
+
- Django and FastAPI/Starlette middleware now time each request as an APM
|
|
6
|
+
transaction (with `apm_enabled`), grouped by URL pattern / route path, with
|
|
7
|
+
errors linked to their request and the browser's `x-errorgap-trace` header
|
|
8
|
+
recorded. `errorgap.django.spans(request)` / `errorgap.fastapi.spans(request)`
|
|
9
|
+
record spans.
|
|
10
|
+
|
|
3
11
|
## 0.2.0 — 2026-10-03
|
|
4
12
|
|
|
5
13
|
- APM: `track_transaction` / `track_job` context managers, `notify_transaction`,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: errorgap
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Python notifier for Errorgap error tracking.
|
|
5
5
|
Project-URL: Homepage, https://github.com/errorgaphq/errorgap-python
|
|
6
6
|
Project-URL: Source, https://github.com/errorgaphq/errorgap-python
|
|
@@ -97,6 +97,11 @@ MIDDLEWARE = [
|
|
|
97
97
|
]
|
|
98
98
|
```
|
|
99
99
|
|
|
100
|
+
With `apm_enabled=True` each request is also an APM transaction grouped by
|
|
101
|
+
its URL pattern (`/orders/<int:order_id>`); errors raised during it carry its
|
|
102
|
+
transaction id, and the browser SDK's `x-errorgap-trace` header is recorded.
|
|
103
|
+
Record spans from a view with `errorgap.django.spans(request).database(sql, ms)`.
|
|
104
|
+
|
|
100
105
|
## Flask
|
|
101
106
|
|
|
102
107
|
```python
|
|
@@ -155,8 +160,8 @@ concurrent threads and asyncio tasks never share one;
|
|
|
155
160
|
## Browser trace links
|
|
156
161
|
|
|
157
162
|
When the errorgap browser SDK (`@errorgap/browser` 0.3+) is on the page, its
|
|
158
|
-
API calls send an `x-errorgap-trace` header. The WSGI
|
|
159
|
-
`init_app`)
|
|
163
|
+
API calls send an `x-errorgap-trace` header. The WSGI, Django and FastAPI
|
|
164
|
+
middleware (and so Flask's `init_app`) record it, and `track_transaction(..., trace_id=header)` accepts
|
|
160
165
|
it, so errorgap's browser Performance view links each call to the server
|
|
161
166
|
request that answered it. Malformed values are ignored.
|
|
162
167
|
|
|
@@ -170,6 +175,12 @@ app = FastAPI()
|
|
|
170
175
|
app.add_middleware(ErrorgapMiddleware)
|
|
171
176
|
```
|
|
172
177
|
|
|
178
|
+
With `apm_enabled=True` each request is also an APM transaction grouped by
|
|
179
|
+
its route path (`/orders/{order_id}`); errors raised during it carry its
|
|
180
|
+
transaction id, and the browser SDK's `x-errorgap-trace` header is recorded.
|
|
181
|
+
Record spans from an endpoint with `errorgap.fastapi.spans(request).database(sql, ms)`
|
|
182
|
+
(take `request: Request` as a parameter).
|
|
183
|
+
|
|
173
184
|
## Configuration reference
|
|
174
185
|
|
|
175
186
|
| Argument | Default | Notes |
|
|
@@ -61,6 +61,11 @@ MIDDLEWARE = [
|
|
|
61
61
|
]
|
|
62
62
|
```
|
|
63
63
|
|
|
64
|
+
With `apm_enabled=True` each request is also an APM transaction grouped by
|
|
65
|
+
its URL pattern (`/orders/<int:order_id>`); errors raised during it carry its
|
|
66
|
+
transaction id, and the browser SDK's `x-errorgap-trace` header is recorded.
|
|
67
|
+
Record spans from a view with `errorgap.django.spans(request).database(sql, ms)`.
|
|
68
|
+
|
|
64
69
|
## Flask
|
|
65
70
|
|
|
66
71
|
```python
|
|
@@ -119,8 +124,8 @@ concurrent threads and asyncio tasks never share one;
|
|
|
119
124
|
## Browser trace links
|
|
120
125
|
|
|
121
126
|
When the errorgap browser SDK (`@errorgap/browser` 0.3+) is on the page, its
|
|
122
|
-
API calls send an `x-errorgap-trace` header. The WSGI
|
|
123
|
-
`init_app`)
|
|
127
|
+
API calls send an `x-errorgap-trace` header. The WSGI, Django and FastAPI
|
|
128
|
+
middleware (and so Flask's `init_app`) record it, and `track_transaction(..., trace_id=header)` accepts
|
|
124
129
|
it, so errorgap's browser Performance view links each call to the server
|
|
125
130
|
request that answered it. Malformed values are ignored.
|
|
126
131
|
|
|
@@ -134,6 +139,12 @@ app = FastAPI()
|
|
|
134
139
|
app.add_middleware(ErrorgapMiddleware)
|
|
135
140
|
```
|
|
136
141
|
|
|
142
|
+
With `apm_enabled=True` each request is also an APM transaction grouped by
|
|
143
|
+
its route path (`/orders/{order_id}`); errors raised during it carry its
|
|
144
|
+
transaction id, and the browser SDK's `x-errorgap-trace` header is recorded.
|
|
145
|
+
Record spans from an endpoint with `errorgap.fastapi.spans(request).database(sql, ms)`
|
|
146
|
+
(take `request: Request` as a parameter).
|
|
147
|
+
|
|
137
148
|
## Configuration reference
|
|
138
149
|
|
|
139
150
|
| Argument | Default | Notes |
|
|
@@ -1,12 +1,22 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import time
|
|
4
|
+
from datetime import datetime, timezone
|
|
3
5
|
from typing import Any, Callable, Dict, Optional
|
|
4
6
|
|
|
5
7
|
from . import notify
|
|
8
|
+
from .apm import SpanCollector, Transaction, browser_trace_id
|
|
9
|
+
from .transaction_context import new_transaction_id, transaction_scope
|
|
10
|
+
|
|
11
|
+
_TRANSACTION_ATTR = "errorgap_transaction"
|
|
6
12
|
|
|
7
13
|
|
|
8
14
|
class ErrorgapMiddleware:
|
|
9
|
-
"""Django middleware that reports unhandled exceptions to Errorgap
|
|
15
|
+
"""Django middleware that reports unhandled exceptions to Errorgap and
|
|
16
|
+
times each request as an APM transaction (sent with ``apm_enabled``),
|
|
17
|
+
grouped by its URL pattern. Errors raised during the request carry its
|
|
18
|
+
transaction id, and the browser SDK's ``x-errorgap-trace`` header links
|
|
19
|
+
the browser's view of the call to it.
|
|
10
20
|
|
|
11
21
|
Add ``"errorgap.django.ErrorgapMiddleware"`` to ``MIDDLEWARE``. Place it
|
|
12
22
|
early so it sees exceptions raised by inner middleware too.
|
|
@@ -16,7 +26,30 @@ class ErrorgapMiddleware:
|
|
|
16
26
|
self.get_response = get_response
|
|
17
27
|
|
|
18
28
|
def __call__(self, request: Any) -> Any:
|
|
19
|
-
|
|
29
|
+
meta = getattr(request, "META", {}) or {}
|
|
30
|
+
txn = Transaction(
|
|
31
|
+
kind="web",
|
|
32
|
+
id=new_transaction_id(),
|
|
33
|
+
trace_id=browser_trace_id(meta.get("HTTP_X_ERRORGAP_TRACE")),
|
|
34
|
+
method=getattr(request, "method", None),
|
|
35
|
+
path_raw=getattr(request, "path", None) or "/",
|
|
36
|
+
occurred_at=datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
37
|
+
)
|
|
38
|
+
try:
|
|
39
|
+
setattr(request, _TRANSACTION_ATTR, txn)
|
|
40
|
+
except Exception: # noqa: BLE001
|
|
41
|
+
pass
|
|
42
|
+
start = time.perf_counter()
|
|
43
|
+
response = None
|
|
44
|
+
try:
|
|
45
|
+
with transaction_scope(txn.id or new_transaction_id()):
|
|
46
|
+
response = self.get_response(request)
|
|
47
|
+
return response
|
|
48
|
+
finally:
|
|
49
|
+
txn.status_code = getattr(response, "status_code", None) or 500
|
|
50
|
+
txn.duration_ms = (time.perf_counter() - start) * 1000.0
|
|
51
|
+
txn.path = _route(request) or txn.path_raw
|
|
52
|
+
_send_transaction(txn)
|
|
20
53
|
|
|
21
54
|
def process_exception(self, request: Any, exception: BaseException) -> Optional[Any]:
|
|
22
55
|
notify(
|
|
@@ -31,6 +64,28 @@ class ErrorgapMiddleware:
|
|
|
31
64
|
return None
|
|
32
65
|
|
|
33
66
|
|
|
67
|
+
def spans(request: Any) -> Optional[SpanCollector]:
|
|
68
|
+
"""The span collector for ``request``'s transaction, for recording DB and
|
|
69
|
+
outbound HTTP spans from views."""
|
|
70
|
+
txn = getattr(request, _TRANSACTION_ATTR, None)
|
|
71
|
+
return txn.spans if txn is not None else None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _route(request: Any) -> Optional[str]:
|
|
75
|
+
"""The matched URL pattern (``/orders/<int:id>``), when one matched."""
|
|
76
|
+
match = getattr(request, "resolver_match", None)
|
|
77
|
+
route = getattr(match, "route", None) if match is not None else None
|
|
78
|
+
if not route:
|
|
79
|
+
return None
|
|
80
|
+
return route if route.startswith("/") else "/" + route
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _send_transaction(txn: Transaction) -> None:
|
|
84
|
+
import errorgap
|
|
85
|
+
|
|
86
|
+
errorgap.notify_transaction(txn)
|
|
87
|
+
|
|
88
|
+
|
|
34
89
|
def _context(request: Any) -> Dict[str, Any]:
|
|
35
90
|
try:
|
|
36
91
|
resolver = getattr(request, "resolver_match", None)
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from typing import Any, Callable, Dict, Optional
|
|
6
|
+
|
|
7
|
+
from . import notify
|
|
8
|
+
from .apm import SpanCollector, Transaction, browser_trace_id
|
|
9
|
+
from .transaction_context import new_transaction_id, transaction_scope
|
|
10
|
+
|
|
11
|
+
#: ASGI scope key holding the request's :class:`~errorgap.apm.Transaction`.
|
|
12
|
+
TRANSACTION_KEY = "errorgap.transaction"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ErrorgapMiddleware:
|
|
16
|
+
"""Pure ASGI middleware that reports unhandled exceptions to Errorgap and
|
|
17
|
+
times each request as an APM transaction (sent with ``apm_enabled``),
|
|
18
|
+
grouped by its route path (``/orders/{order_id}``). Errors raised during
|
|
19
|
+
the request carry its transaction id, and the browser SDK's
|
|
20
|
+
``x-errorgap-trace`` header links the browser's view of the call to it.
|
|
21
|
+
|
|
22
|
+
Usage::
|
|
23
|
+
|
|
24
|
+
from fastapi import FastAPI
|
|
25
|
+
from errorgap.fastapi import ErrorgapMiddleware
|
|
26
|
+
|
|
27
|
+
app = FastAPI()
|
|
28
|
+
app.add_middleware(ErrorgapMiddleware)
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(self, app: Callable[..., Any]) -> None:
|
|
32
|
+
self.app = app
|
|
33
|
+
|
|
34
|
+
async def __call__(self, scope: Dict[str, Any], receive: Callable, send: Callable) -> None:
|
|
35
|
+
if scope.get("type") != "http":
|
|
36
|
+
await self.app(scope, receive, send)
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
headers = dict(scope.get("headers", []))
|
|
40
|
+
txn = Transaction(
|
|
41
|
+
kind="web",
|
|
42
|
+
id=new_transaction_id(),
|
|
43
|
+
trace_id=browser_trace_id(headers.get(b"x-errorgap-trace")),
|
|
44
|
+
method=scope.get("method"),
|
|
45
|
+
path_raw=scope.get("path") or "/",
|
|
46
|
+
occurred_at=datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
47
|
+
)
|
|
48
|
+
scope[TRANSACTION_KEY] = txn
|
|
49
|
+
start = time.perf_counter()
|
|
50
|
+
|
|
51
|
+
async def _send(message: Dict[str, Any]) -> None:
|
|
52
|
+
if message.get("type") == "http.response.start":
|
|
53
|
+
txn.status_code = message.get("status")
|
|
54
|
+
await send(message)
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
with transaction_scope(txn.id or new_transaction_id()):
|
|
58
|
+
try:
|
|
59
|
+
await self.app(scope, receive, _send)
|
|
60
|
+
except Exception as exc:
|
|
61
|
+
txn.status_code = 500
|
|
62
|
+
notify(
|
|
63
|
+
exc,
|
|
64
|
+
sync=True,
|
|
65
|
+
context=_context(scope),
|
|
66
|
+
environment=_environment(scope),
|
|
67
|
+
)
|
|
68
|
+
raise
|
|
69
|
+
finally:
|
|
70
|
+
import errorgap
|
|
71
|
+
|
|
72
|
+
txn.duration_ms = (time.perf_counter() - start) * 1000.0
|
|
73
|
+
txn.path = _route(scope) or txn.path_raw
|
|
74
|
+
if txn.status_code is None:
|
|
75
|
+
txn.status_code = 500
|
|
76
|
+
errorgap.notify_transaction(txn)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def spans(request: Any) -> Optional[SpanCollector]:
|
|
80
|
+
"""The span collector for the request's transaction (a Starlette/FastAPI
|
|
81
|
+
``Request``), for recording DB and outbound HTTP spans from endpoints."""
|
|
82
|
+
txn = getattr(request, "scope", {}).get(TRANSACTION_KEY)
|
|
83
|
+
return txn.spans if txn is not None else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _route(scope: Dict[str, Any]) -> Optional[str]:
|
|
87
|
+
"""The matched route's path template, which FastAPI's router records."""
|
|
88
|
+
route = scope.get("route")
|
|
89
|
+
path = getattr(route, "path", None)
|
|
90
|
+
return path if isinstance(path, str) and path else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _context(scope: Dict[str, Any]) -> Dict[str, Any]:
|
|
94
|
+
return {
|
|
95
|
+
"url": _build_url(scope),
|
|
96
|
+
"component": scope.get("path"),
|
|
97
|
+
"action": scope.get("method"),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _environment(scope: Dict[str, Any]) -> Dict[str, Any]:
|
|
102
|
+
headers = {k.decode("latin1"): v.decode("latin1") for k, v in scope.get("headers", [])}
|
|
103
|
+
client = scope.get("client") or (None, None)
|
|
104
|
+
return {
|
|
105
|
+
"method": scope.get("method"),
|
|
106
|
+
"path": scope.get("path"),
|
|
107
|
+
"query_string": scope.get("query_string", b"").decode("utf-8", errors="replace"),
|
|
108
|
+
"user_agent": headers.get("user-agent"),
|
|
109
|
+
"remote_addr": client[0],
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _build_url(scope: Dict[str, Any]) -> str:
|
|
114
|
+
scheme = scope.get("scheme", "http")
|
|
115
|
+
headers = dict(scope.get("headers", []))
|
|
116
|
+
host = headers.get(b"host", b"").decode("latin1") or "localhost"
|
|
117
|
+
path = scope.get("path", "/")
|
|
118
|
+
query = scope.get("query_string", b"").decode("utf-8", errors="replace")
|
|
119
|
+
suffix = f"?{query}" if query else ""
|
|
120
|
+
return f"{scheme}://{host}{path}{suffix}"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
VERSION = "0.3.0"
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
django = pytest.importorskip("django")
|
|
6
|
+
|
|
7
|
+
from django.conf import settings
|
|
8
|
+
from django.http import HttpResponse
|
|
9
|
+
from django.test import RequestFactory
|
|
10
|
+
from django.urls import path
|
|
11
|
+
|
|
12
|
+
import errorgap
|
|
13
|
+
from errorgap.django import ErrorgapMiddleware
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.fixture(scope="module", autouse=True)
|
|
17
|
+
def _django_setup():
|
|
18
|
+
if not settings.configured:
|
|
19
|
+
settings.configure(
|
|
20
|
+
DEBUG=False,
|
|
21
|
+
ALLOWED_HOSTS=["*"],
|
|
22
|
+
ROOT_URLCONF=__name__,
|
|
23
|
+
DATABASES={},
|
|
24
|
+
INSTALLED_APPS=[],
|
|
25
|
+
MIDDLEWARE=[],
|
|
26
|
+
SECRET_KEY="test",
|
|
27
|
+
DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
|
|
28
|
+
)
|
|
29
|
+
import django as _django
|
|
30
|
+
|
|
31
|
+
_django.setup()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _boom(_request):
|
|
35
|
+
raise RuntimeError("django-boom")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
urlpatterns = [path("boom", _boom)]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_middleware_reports_exception(ingestor, reset_errorgap):
|
|
42
|
+
errorgap.init(
|
|
43
|
+
endpoint=ingestor.endpoint,
|
|
44
|
+
project_slug="demo",
|
|
45
|
+
api_key="flk_test",
|
|
46
|
+
async_=False,
|
|
47
|
+
capture_globals=False,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
factory = RequestFactory()
|
|
51
|
+
request = factory.get("/boom?x=1")
|
|
52
|
+
|
|
53
|
+
middleware = ErrorgapMiddleware(get_response=lambda req: HttpResponse(""))
|
|
54
|
+
|
|
55
|
+
try:
|
|
56
|
+
_boom(request)
|
|
57
|
+
except RuntimeError as exc:
|
|
58
|
+
middleware.process_exception(request, exc)
|
|
59
|
+
|
|
60
|
+
errorgap.flush(timeout=5)
|
|
61
|
+
assert len(ingestor.requests) == 1
|
|
62
|
+
body = ingestor.requests[0].body
|
|
63
|
+
assert body["errors"][0]["type"] == "RuntimeError"
|
|
64
|
+
assert body["errors"][0]["message"] == "django-boom"
|
|
65
|
+
assert body["context"]["action"] == "GET"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _order(request, order_id):
|
|
69
|
+
from errorgap.django import spans
|
|
70
|
+
|
|
71
|
+
spans(request).database("SELECT * FROM orders WHERE id = %d" % order_id, 1.0)
|
|
72
|
+
errorgap.notify(RuntimeError("card declined"))
|
|
73
|
+
return HttpResponse("ok", status=201)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
urlpatterns.append(path("orders/<int:order_id>", _order))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_requests_are_transactions_linked_to_their_errors(ingestor, reset_errorgap):
|
|
80
|
+
from django.test import Client
|
|
81
|
+
|
|
82
|
+
errorgap.init(
|
|
83
|
+
endpoint=ingestor.endpoint,
|
|
84
|
+
project_slug="demo",
|
|
85
|
+
async_=False,
|
|
86
|
+
capture_globals=False,
|
|
87
|
+
apm_enabled=True,
|
|
88
|
+
)
|
|
89
|
+
settings.MIDDLEWARE = ["errorgap.django.ErrorgapMiddleware"]
|
|
90
|
+
try:
|
|
91
|
+
client = Client(raise_request_exception=False)
|
|
92
|
+
ok = client.get("/orders/7", HTTP_X_ERRORGAP_TRACE="0192F3C4-7A1B-4C2D-9E3F-0123456789AB")
|
|
93
|
+
boom = client.get("/boom")
|
|
94
|
+
finally:
|
|
95
|
+
settings.MIDDLEWARE = []
|
|
96
|
+
assert ok.status_code == 201
|
|
97
|
+
assert boom.status_code == 500
|
|
98
|
+
|
|
99
|
+
txns = [r.body for r in ingestor.requests if r.path.endswith("/transactions")]
|
|
100
|
+
notices = [r.body for r in ingestor.requests if r.path.endswith("/notices")]
|
|
101
|
+
ok_txn = next(t for t in txns if t["path_raw"] == "/orders/7")
|
|
102
|
+
boom_txn = next(t for t in txns if t["path_raw"] == "/boom")
|
|
103
|
+
assert ok_txn["path"] == "/orders/<int:order_id>"
|
|
104
|
+
assert ok_txn["status_code"] == 201
|
|
105
|
+
assert ok_txn["trace_id"] == "0192f3c4-7a1b-4c2d-9e3f-0123456789ab"
|
|
106
|
+
assert ok_txn["spans"][0]["sql"] == "SELECT * FROM orders WHERE id = ?"
|
|
107
|
+
assert boom_txn["status_code"] == 500
|
|
108
|
+
assert "trace_id" not in boom_txn
|
|
109
|
+
by_message = {n["errors"][0]["message"]: n["context"].get("transaction_id") for n in notices}
|
|
110
|
+
assert by_message["card declined"] == ok_txn["id"]
|
|
111
|
+
assert by_message["django-boom"] == boom_txn["id"]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
fastapi = pytest.importorskip("fastapi")
|
|
6
|
+
|
|
7
|
+
from fastapi import FastAPI, Request
|
|
8
|
+
from starlette.testclient import TestClient
|
|
9
|
+
|
|
10
|
+
import errorgap
|
|
11
|
+
from errorgap.fastapi import ErrorgapMiddleware, spans
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_fastapi_middleware_reports_exception(ingestor, reset_errorgap):
|
|
15
|
+
errorgap.init(
|
|
16
|
+
endpoint=ingestor.endpoint,
|
|
17
|
+
project_slug="demo",
|
|
18
|
+
api_key="flk_test",
|
|
19
|
+
async_=False,
|
|
20
|
+
capture_globals=False,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
app = FastAPI()
|
|
24
|
+
app.add_middleware(ErrorgapMiddleware)
|
|
25
|
+
|
|
26
|
+
@app.get("/boom")
|
|
27
|
+
def boom():
|
|
28
|
+
raise RuntimeError("fastapi-boom")
|
|
29
|
+
|
|
30
|
+
client = TestClient(app, raise_server_exceptions=False)
|
|
31
|
+
response = client.get("/boom?x=1")
|
|
32
|
+
assert response.status_code == 500
|
|
33
|
+
|
|
34
|
+
errorgap.flush(timeout=5)
|
|
35
|
+
assert len(ingestor.requests) == 1
|
|
36
|
+
body = ingestor.requests[0].body
|
|
37
|
+
assert body["errors"][0]["type"] == "RuntimeError"
|
|
38
|
+
assert body["errors"][0]["message"] == "fastapi-boom"
|
|
39
|
+
assert body["context"]["action"] == "GET"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_fastapi_requests_are_transactions_linked_to_their_errors(ingestor, reset_errorgap):
|
|
43
|
+
errorgap.init(
|
|
44
|
+
endpoint=ingestor.endpoint,
|
|
45
|
+
project_slug="demo",
|
|
46
|
+
async_=False,
|
|
47
|
+
capture_globals=False,
|
|
48
|
+
apm_enabled=True,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
app = FastAPI()
|
|
52
|
+
app.add_middleware(ErrorgapMiddleware)
|
|
53
|
+
|
|
54
|
+
@app.get("/orders/{order_id}", status_code=201)
|
|
55
|
+
async def order(order_id: int, request: Request):
|
|
56
|
+
spans(request).database("SELECT * FROM orders WHERE id = %d" % order_id, 1.0)
|
|
57
|
+
errorgap.notify(RuntimeError("card declined"))
|
|
58
|
+
return {"id": order_id}
|
|
59
|
+
|
|
60
|
+
@app.get("/sync/{n}")
|
|
61
|
+
def sync_boom(n: int):
|
|
62
|
+
raise RuntimeError("fastapi-boom")
|
|
63
|
+
|
|
64
|
+
client = TestClient(app, raise_server_exceptions=False)
|
|
65
|
+
ok = client.get("/orders/7", headers={"x-errorgap-trace": "0192F3C4-7A1B-4C2D-9E3F-0123456789AB"})
|
|
66
|
+
boom = client.get("/sync/1")
|
|
67
|
+
assert ok.status_code == 201
|
|
68
|
+
assert boom.status_code == 500
|
|
69
|
+
|
|
70
|
+
txns = [r.body for r in ingestor.requests if r.path.endswith("/transactions")]
|
|
71
|
+
notices = [r.body for r in ingestor.requests if r.path.endswith("/notices")]
|
|
72
|
+
ok_txn = next(t for t in txns if t["path_raw"] == "/orders/7")
|
|
73
|
+
boom_txn = next(t for t in txns if t["path_raw"] == "/sync/1")
|
|
74
|
+
assert ok_txn["path"] == "/orders/{order_id}"
|
|
75
|
+
assert ok_txn["status_code"] == 201
|
|
76
|
+
assert ok_txn["trace_id"] == "0192f3c4-7a1b-4c2d-9e3f-0123456789ab"
|
|
77
|
+
assert ok_txn["spans"][0]["sql"] == "SELECT * FROM orders WHERE id = ?"
|
|
78
|
+
assert boom_txn["path"] == "/sync/{n}"
|
|
79
|
+
assert boom_txn["status_code"] == 500
|
|
80
|
+
by_message = {n["errors"][0]["message"]: n["context"].get("transaction_id") for n in notices}
|
|
81
|
+
assert by_message["card declined"] == ok_txn["id"]
|
|
82
|
+
assert by_message["fastapi-boom"] == boom_txn["id"]
|
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
from typing import Any, Callable, Dict
|
|
4
|
-
|
|
5
|
-
from . import notify
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class ErrorgapMiddleware:
|
|
9
|
-
"""Pure ASGI middleware that reports unhandled exceptions to Errorgap.
|
|
10
|
-
|
|
11
|
-
Usage::
|
|
12
|
-
|
|
13
|
-
from fastapi import FastAPI
|
|
14
|
-
from errorgap.fastapi import ErrorgapMiddleware
|
|
15
|
-
|
|
16
|
-
app = FastAPI()
|
|
17
|
-
app.add_middleware(ErrorgapMiddleware)
|
|
18
|
-
"""
|
|
19
|
-
|
|
20
|
-
def __init__(self, app: Callable[..., Any]) -> None:
|
|
21
|
-
self.app = app
|
|
22
|
-
|
|
23
|
-
async def __call__(self, scope: Dict[str, Any], receive: Callable, send: Callable) -> None:
|
|
24
|
-
if scope.get("type") != "http":
|
|
25
|
-
await self.app(scope, receive, send)
|
|
26
|
-
return
|
|
27
|
-
|
|
28
|
-
try:
|
|
29
|
-
await self.app(scope, receive, send)
|
|
30
|
-
except Exception as exc:
|
|
31
|
-
notify(
|
|
32
|
-
exc,
|
|
33
|
-
sync=True,
|
|
34
|
-
context=_context(scope),
|
|
35
|
-
environment=_environment(scope),
|
|
36
|
-
)
|
|
37
|
-
raise
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
def _context(scope: Dict[str, Any]) -> Dict[str, Any]:
|
|
41
|
-
return {
|
|
42
|
-
"url": _build_url(scope),
|
|
43
|
-
"component": scope.get("path"),
|
|
44
|
-
"action": scope.get("method"),
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
def _environment(scope: Dict[str, Any]) -> Dict[str, Any]:
|
|
49
|
-
headers = {k.decode("latin1"): v.decode("latin1") for k, v in scope.get("headers", [])}
|
|
50
|
-
client = scope.get("client") or (None, None)
|
|
51
|
-
return {
|
|
52
|
-
"method": scope.get("method"),
|
|
53
|
-
"path": scope.get("path"),
|
|
54
|
-
"query_string": scope.get("query_string", b"").decode("utf-8", errors="replace"),
|
|
55
|
-
"user_agent": headers.get("user-agent"),
|
|
56
|
-
"remote_addr": client[0],
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
def _build_url(scope: Dict[str, Any]) -> str:
|
|
61
|
-
scheme = scope.get("scheme", "http")
|
|
62
|
-
headers = dict(scope.get("headers", []))
|
|
63
|
-
host = headers.get(b"host", b"").decode("latin1") or "localhost"
|
|
64
|
-
path = scope.get("path", "/")
|
|
65
|
-
query = scope.get("query_string", b"").decode("utf-8", errors="replace")
|
|
66
|
-
suffix = f"?{query}" if query else ""
|
|
67
|
-
return f"{scheme}://{host}{path}{suffix}"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
VERSION = "0.2.0"
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import pytest
|
|
4
|
-
|
|
5
|
-
django = pytest.importorskip("django")
|
|
6
|
-
|
|
7
|
-
from django.conf import settings
|
|
8
|
-
from django.http import HttpResponse
|
|
9
|
-
from django.test import RequestFactory
|
|
10
|
-
from django.urls import path
|
|
11
|
-
|
|
12
|
-
import errorgap
|
|
13
|
-
from errorgap.django import ErrorgapMiddleware
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
@pytest.fixture(scope="module", autouse=True)
|
|
17
|
-
def _django_setup():
|
|
18
|
-
if not settings.configured:
|
|
19
|
-
settings.configure(
|
|
20
|
-
DEBUG=False,
|
|
21
|
-
ALLOWED_HOSTS=["*"],
|
|
22
|
-
ROOT_URLCONF=__name__,
|
|
23
|
-
DATABASES={},
|
|
24
|
-
INSTALLED_APPS=[],
|
|
25
|
-
MIDDLEWARE=[],
|
|
26
|
-
SECRET_KEY="test",
|
|
27
|
-
DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
|
|
28
|
-
)
|
|
29
|
-
import django as _django
|
|
30
|
-
|
|
31
|
-
_django.setup()
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
def _boom(_request):
|
|
35
|
-
raise RuntimeError("django-boom")
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
urlpatterns = [path("boom", _boom)]
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def test_middleware_reports_exception(ingestor, reset_errorgap):
|
|
42
|
-
errorgap.init(
|
|
43
|
-
endpoint=ingestor.endpoint,
|
|
44
|
-
project_slug="demo",
|
|
45
|
-
api_key="flk_test",
|
|
46
|
-
async_=False,
|
|
47
|
-
capture_globals=False,
|
|
48
|
-
)
|
|
49
|
-
|
|
50
|
-
factory = RequestFactory()
|
|
51
|
-
request = factory.get("/boom?x=1")
|
|
52
|
-
|
|
53
|
-
middleware = ErrorgapMiddleware(get_response=lambda req: HttpResponse(""))
|
|
54
|
-
|
|
55
|
-
try:
|
|
56
|
-
_boom(request)
|
|
57
|
-
except RuntimeError as exc:
|
|
58
|
-
middleware.process_exception(request, exc)
|
|
59
|
-
|
|
60
|
-
errorgap.flush(timeout=5)
|
|
61
|
-
assert len(ingestor.requests) == 1
|
|
62
|
-
body = ingestor.requests[0].body
|
|
63
|
-
assert body["errors"][0]["type"] == "RuntimeError"
|
|
64
|
-
assert body["errors"][0]["message"] == "django-boom"
|
|
65
|
-
assert body["context"]["action"] == "GET"
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import pytest
|
|
4
|
-
|
|
5
|
-
fastapi = pytest.importorskip("fastapi")
|
|
6
|
-
|
|
7
|
-
from fastapi import FastAPI
|
|
8
|
-
from starlette.testclient import TestClient
|
|
9
|
-
|
|
10
|
-
import errorgap
|
|
11
|
-
from errorgap.fastapi import ErrorgapMiddleware
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def test_fastapi_middleware_reports_exception(ingestor, reset_errorgap):
|
|
15
|
-
errorgap.init(
|
|
16
|
-
endpoint=ingestor.endpoint,
|
|
17
|
-
project_slug="demo",
|
|
18
|
-
api_key="flk_test",
|
|
19
|
-
async_=False,
|
|
20
|
-
capture_globals=False,
|
|
21
|
-
)
|
|
22
|
-
|
|
23
|
-
app = FastAPI()
|
|
24
|
-
app.add_middleware(ErrorgapMiddleware)
|
|
25
|
-
|
|
26
|
-
@app.get("/boom")
|
|
27
|
-
def boom():
|
|
28
|
-
raise RuntimeError("fastapi-boom")
|
|
29
|
-
|
|
30
|
-
client = TestClient(app, raise_server_exceptions=False)
|
|
31
|
-
response = client.get("/boom?x=1")
|
|
32
|
-
assert response.status_code == 500
|
|
33
|
-
|
|
34
|
-
errorgap.flush(timeout=5)
|
|
35
|
-
assert len(ingestor.requests) == 1
|
|
36
|
-
body = ingestor.requests[0].body
|
|
37
|
-
assert body["errors"][0]["type"] == "RuntimeError"
|
|
38
|
-
assert body["errors"][0]["message"] == "fastapi-boom"
|
|
39
|
-
assert body["context"]["action"] == "GET"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|