centralog-sdk 0.1.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.
- centralog_sdk-0.1.0/.gitignore +8 -0
- centralog_sdk-0.1.0/LICENSE +21 -0
- centralog_sdk-0.1.0/PKG-INFO +138 -0
- centralog_sdk-0.1.0/README.md +113 -0
- centralog_sdk-0.1.0/centralog/__init__.py +7 -0
- centralog_sdk-0.1.0/centralog/client.py +92 -0
- centralog_sdk-0.1.0/centralog/frameworks/__init__.py +0 -0
- centralog_sdk-0.1.0/centralog/frameworks/django.py +37 -0
- centralog_sdk-0.1.0/centralog/frameworks/fastapi.py +59 -0
- centralog_sdk-0.1.0/centralog/frameworks/flask.py +38 -0
- centralog_sdk-0.1.0/centralog/payload.py +47 -0
- centralog_sdk-0.1.0/pyproject.toml +31 -0
- centralog_sdk-0.1.0/tests/test_client.py +112 -0
- centralog_sdk-0.1.0/tests/test_django.py +100 -0
- centralog_sdk-0.1.0/tests/test_fastapi.py +40 -0
- centralog_sdk-0.1.0/tests/test_flask.py +60 -0
- centralog_sdk-0.1.0/tests/test_payload.py +73 -0
- centralog_sdk-0.1.0/uv.lock +728 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jesus Yair Juarez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: centralog-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for Centralog error monitoring. Captures exceptions and sends a copy to your Centralog platform without breaking your app.
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: centralog,django,error-monitoring,fastapi,flask
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: httpx>=0.27
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: django>=4.2; extra == 'dev'
|
|
12
|
+
Requires-Dist: fastapi>=0.110; extra == 'dev'
|
|
13
|
+
Requires-Dist: flask>=3.0; extra == 'dev'
|
|
14
|
+
Requires-Dist: httpx>=0.27; extra == 'dev'
|
|
15
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
16
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
17
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
18
|
+
Provides-Extra: django
|
|
19
|
+
Requires-Dist: django>=4.2; extra == 'django'
|
|
20
|
+
Provides-Extra: fastapi
|
|
21
|
+
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
|
|
22
|
+
Provides-Extra: flask
|
|
23
|
+
Requires-Dist: flask>=3.0; extra == 'flask'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# Centralog SDK — Python
|
|
27
|
+
|
|
28
|
+
Python SDK for [Centralog](https://github.com/Thejairex/centralog) error monitoring.
|
|
29
|
+
Captures exceptions and sends a copy to your Centralog platform. Never breaks your app.
|
|
30
|
+
|
|
31
|
+
Supports **FastAPI**, **Flask** and **Django** (plus manual capture anywhere).
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install centralog-sdk
|
|
37
|
+
# with framework support:
|
|
38
|
+
pip install "centralog-sdk[fastapi]"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Configure
|
|
42
|
+
|
|
43
|
+
Env vars:
|
|
44
|
+
|
|
45
|
+
```env
|
|
46
|
+
CENTRALOG_ENABLED=true
|
|
47
|
+
CENTRALOG_ENDPOINT=https://centralog.tudominio.com/api/v1/ingest/events
|
|
48
|
+
CENTRALOG_API_KEY=clk_tu_api_key
|
|
49
|
+
CENTRALOG_ENVIRONMENT=production
|
|
50
|
+
CENTRALOG_RELEASE=2026.09.30.1
|
|
51
|
+
CENTRALOG_TIMEOUT=2
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Generate the API key in Centralog: Projects → API Keys.
|
|
55
|
+
|
|
56
|
+
## Usage
|
|
57
|
+
|
|
58
|
+
**FastAPI** (one line):
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from fastapi import FastAPI
|
|
62
|
+
from centralog.frameworks.fastapi import register as centralog_register
|
|
63
|
+
|
|
64
|
+
app = FastAPI()
|
|
65
|
+
centralog_register(app)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Flask**:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from flask import Flask
|
|
72
|
+
from centralog.frameworks.flask import register as centralog_register
|
|
73
|
+
|
|
74
|
+
app = Flask(__name__)
|
|
75
|
+
centralog_register(app)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
**Django** — add to `MIDDLEWARE`:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
MIDDLEWARE = [
|
|
82
|
+
...,
|
|
83
|
+
"centralog.frameworks.django.CentralogMiddleware",
|
|
84
|
+
]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**Manual** (anywhere):
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from centralog import CentralogClient
|
|
91
|
+
|
|
92
|
+
client = CentralogClient()
|
|
93
|
+
client.context({"tenant": "acme"})
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
charge(order)
|
|
97
|
+
except Exception as exc:
|
|
98
|
+
client.capture(exc, {"order_id": order.id})
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Your local logging keeps working as always — the SDK only sends a **copy** to Centralog.
|
|
102
|
+
|
|
103
|
+
## Custom errors
|
|
104
|
+
|
|
105
|
+
Any exception (including your domain exceptions) can be captured manually
|
|
106
|
+
with a level (`error`, `warning`, `info` or `debug`):
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from centralog import CentralogClient
|
|
110
|
+
|
|
111
|
+
class PaymentFailedError(Exception):
|
|
112
|
+
pass
|
|
113
|
+
|
|
114
|
+
client = CentralogClient()
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
charge(order)
|
|
118
|
+
except PaymentFailedError as exc:
|
|
119
|
+
client.capture(exc, {"order_id": order.id}, level="warning")
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Each exception is grouped in Centralog by **class + file + line**, so every
|
|
123
|
+
custom exception in your domain gets its own group in the panel.
|
|
124
|
+
|
|
125
|
+
Valid levels: `error` (default), `warning`, `info`, `debug`.
|
|
126
|
+
|
|
127
|
+
## Safety
|
|
128
|
+
|
|
129
|
+
- Short timeout (2s default), never blocks a request for long.
|
|
130
|
+
- Any network failure is swallowed and logged with `logging.debug`.
|
|
131
|
+
- Disabled automatically when `CENTRALOG_ENABLED=false` or endpoint/key are missing.
|
|
132
|
+
- No workers required (synchronous by design).
|
|
133
|
+
|
|
134
|
+
## Testing
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
uv run pytest
|
|
138
|
+
```
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Centralog SDK — Python
|
|
2
|
+
|
|
3
|
+
Python SDK for [Centralog](https://github.com/Thejairex/centralog) error monitoring.
|
|
4
|
+
Captures exceptions and sends a copy to your Centralog platform. Never breaks your app.
|
|
5
|
+
|
|
6
|
+
Supports **FastAPI**, **Flask** and **Django** (plus manual capture anywhere).
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install centralog-sdk
|
|
12
|
+
# with framework support:
|
|
13
|
+
pip install "centralog-sdk[fastapi]"
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Configure
|
|
17
|
+
|
|
18
|
+
Env vars:
|
|
19
|
+
|
|
20
|
+
```env
|
|
21
|
+
CENTRALOG_ENABLED=true
|
|
22
|
+
CENTRALOG_ENDPOINT=https://centralog.tudominio.com/api/v1/ingest/events
|
|
23
|
+
CENTRALOG_API_KEY=clk_tu_api_key
|
|
24
|
+
CENTRALOG_ENVIRONMENT=production
|
|
25
|
+
CENTRALOG_RELEASE=2026.09.30.1
|
|
26
|
+
CENTRALOG_TIMEOUT=2
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Generate the API key in Centralog: Projects → API Keys.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
**FastAPI** (one line):
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from fastapi import FastAPI
|
|
37
|
+
from centralog.frameworks.fastapi import register as centralog_register
|
|
38
|
+
|
|
39
|
+
app = FastAPI()
|
|
40
|
+
centralog_register(app)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Flask**:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from flask import Flask
|
|
47
|
+
from centralog.frameworks.flask import register as centralog_register
|
|
48
|
+
|
|
49
|
+
app = Flask(__name__)
|
|
50
|
+
centralog_register(app)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
**Django** — add to `MIDDLEWARE`:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
MIDDLEWARE = [
|
|
57
|
+
...,
|
|
58
|
+
"centralog.frameworks.django.CentralogMiddleware",
|
|
59
|
+
]
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**Manual** (anywhere):
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from centralog import CentralogClient
|
|
66
|
+
|
|
67
|
+
client = CentralogClient()
|
|
68
|
+
client.context({"tenant": "acme"})
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
charge(order)
|
|
72
|
+
except Exception as exc:
|
|
73
|
+
client.capture(exc, {"order_id": order.id})
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Your local logging keeps working as always — the SDK only sends a **copy** to Centralog.
|
|
77
|
+
|
|
78
|
+
## Custom errors
|
|
79
|
+
|
|
80
|
+
Any exception (including your domain exceptions) can be captured manually
|
|
81
|
+
with a level (`error`, `warning`, `info` or `debug`):
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from centralog import CentralogClient
|
|
85
|
+
|
|
86
|
+
class PaymentFailedError(Exception):
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
client = CentralogClient()
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
charge(order)
|
|
93
|
+
except PaymentFailedError as exc:
|
|
94
|
+
client.capture(exc, {"order_id": order.id}, level="warning")
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Each exception is grouped in Centralog by **class + file + line**, so every
|
|
98
|
+
custom exception in your domain gets its own group in the panel.
|
|
99
|
+
|
|
100
|
+
Valid levels: `error` (default), `warning`, `info`, `debug`.
|
|
101
|
+
|
|
102
|
+
## Safety
|
|
103
|
+
|
|
104
|
+
- Short timeout (2s default), never blocks a request for long.
|
|
105
|
+
- Any network failure is swallowed and logged with `logging.debug`.
|
|
106
|
+
- Disabled automatically when `CENTRALOG_ENABLED=false` or endpoint/key are missing.
|
|
107
|
+
- No workers required (synchronous by design).
|
|
108
|
+
|
|
109
|
+
## Testing
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
uv run pytest
|
|
113
|
+
```
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Fault-tolerant HTTP client for the Centralog ingest API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .payload import build_payload
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger("centralog")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CentralogClient:
|
|
17
|
+
"""Send error copies to Centralog. Never raises."""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
endpoint: str | None = None,
|
|
22
|
+
api_key: str | None = None,
|
|
23
|
+
environment: str | None = None,
|
|
24
|
+
release: str | None = None,
|
|
25
|
+
timeout: float = 2.0,
|
|
26
|
+
enabled: bool = True,
|
|
27
|
+
) -> None:
|
|
28
|
+
self.endpoint = endpoint or os.getenv("CENTRALOG_ENDPOINT", "")
|
|
29
|
+
self.api_key = api_key or os.getenv("CENTRALOG_API_KEY", "")
|
|
30
|
+
self.environment = environment or os.getenv("CENTRALOG_ENVIRONMENT", "production")
|
|
31
|
+
self.release = release if release is not None else os.getenv("CENTRALOG_RELEASE")
|
|
32
|
+
self.timeout = timeout
|
|
33
|
+
if (env_timeout := os.getenv("CENTRALOG_TIMEOUT")) and timeout == 2.0:
|
|
34
|
+
try:
|
|
35
|
+
self.timeout = float(env_timeout)
|
|
36
|
+
except ValueError:
|
|
37
|
+
pass
|
|
38
|
+
self.enabled = enabled and os.getenv("CENTRALOG_ENABLED", "true").lower() not in (
|
|
39
|
+
"0",
|
|
40
|
+
"false",
|
|
41
|
+
"no",
|
|
42
|
+
"off",
|
|
43
|
+
)
|
|
44
|
+
self._extra_context: dict[str, Any] = {}
|
|
45
|
+
|
|
46
|
+
def context(self, context: dict[str, Any]) -> None:
|
|
47
|
+
"""Merge extra context into every captured event."""
|
|
48
|
+
self._extra_context.update(context)
|
|
49
|
+
|
|
50
|
+
def get_context(self) -> dict[str, Any]:
|
|
51
|
+
return dict(self._extra_context)
|
|
52
|
+
|
|
53
|
+
def flush_context(self) -> None:
|
|
54
|
+
self._extra_context = {}
|
|
55
|
+
|
|
56
|
+
def capture(
|
|
57
|
+
self,
|
|
58
|
+
exception: BaseException,
|
|
59
|
+
context: dict[str, Any] | None = None,
|
|
60
|
+
level: str = "error",
|
|
61
|
+
request: dict[str, Any] | None = None,
|
|
62
|
+
user: dict[str, Any] | None = None,
|
|
63
|
+
) -> bool:
|
|
64
|
+
"""Capture an exception and send a copy to Centralog.
|
|
65
|
+
|
|
66
|
+
Returns True on success. Never raises: any failure is logged
|
|
67
|
+
locally at debug level and swallowed.
|
|
68
|
+
"""
|
|
69
|
+
if not self.enabled or not self.endpoint or not self.api_key:
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
merged = {**self._extra_context, **(context or {})}
|
|
74
|
+
payload = build_payload(
|
|
75
|
+
exception,
|
|
76
|
+
environment=self.environment,
|
|
77
|
+
release=self.release,
|
|
78
|
+
level=level,
|
|
79
|
+
context=merged,
|
|
80
|
+
request=request,
|
|
81
|
+
user=user,
|
|
82
|
+
)
|
|
83
|
+
response = httpx.post(
|
|
84
|
+
self.endpoint,
|
|
85
|
+
json=payload,
|
|
86
|
+
headers={"Authorization": f"Bearer {self.api_key}"},
|
|
87
|
+
timeout=self.timeout,
|
|
88
|
+
)
|
|
89
|
+
return 200 <= response.status_code < 300
|
|
90
|
+
except Exception as exc: # noqa: BLE001 — reporting must never break the app
|
|
91
|
+
logger.debug("Centralog reporting failed: %s", exc)
|
|
92
|
+
return False
|
|
File without changes
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Django integration: middleware that reports unhandled exceptions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from ..client import CentralogClient
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger("centralog")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CentralogMiddleware:
|
|
13
|
+
"""Report unhandled exceptions, then re-raise so Django handles them.
|
|
14
|
+
|
|
15
|
+
Add to MIDDLEWARE. Never swallows: the exception always propagates.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, get_response): # type: ignore[no-untyped-def]
|
|
19
|
+
self.get_response = get_response
|
|
20
|
+
self.client = CentralogClient()
|
|
21
|
+
|
|
22
|
+
def __call__(self, request): # type: ignore[no-untyped-def]
|
|
23
|
+
return self.get_response(request)
|
|
24
|
+
|
|
25
|
+
def process_exception(self, request, exception) -> None: # type: ignore[no-untyped-def]
|
|
26
|
+
try:
|
|
27
|
+
resolver_match = getattr(request, "resolver_match", None)
|
|
28
|
+
self.client.capture(
|
|
29
|
+
exception,
|
|
30
|
+
request={
|
|
31
|
+
"method": request.method,
|
|
32
|
+
"url": request.build_absolute_uri(),
|
|
33
|
+
"route": getattr(resolver_match, "view_name", None),
|
|
34
|
+
},
|
|
35
|
+
)
|
|
36
|
+
except Exception as exc: # noqa: BLE001 — reporting must never break the app
|
|
37
|
+
logger.debug("Centralog Django middleware failed: %s", exc)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""FastAPI integration: register an exception handler that reports 500s."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from fastapi import FastAPI, Request
|
|
9
|
+
from fastapi.responses import JSONResponse
|
|
10
|
+
except ImportError: # pragma: no cover
|
|
11
|
+
FastAPI = None # type: ignore[assignment]
|
|
12
|
+
Request = None # type: ignore[assignment]
|
|
13
|
+
JSONResponse = None # type: ignore[assignment]
|
|
14
|
+
|
|
15
|
+
from ..client import CentralogClient
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def register(
|
|
19
|
+
app: FastAPI,
|
|
20
|
+
client: CentralogClient | None = None,
|
|
21
|
+
*,
|
|
22
|
+
capture_http_exceptions: bool = False,
|
|
23
|
+
) -> CentralogClient:
|
|
24
|
+
"""Register Centralog error reporting on a FastAPI app.
|
|
25
|
+
|
|
26
|
+
Captures unhandled 500s (and optionally HTTPException) without
|
|
27
|
+
changing the responses your app returns.
|
|
28
|
+
"""
|
|
29
|
+
client = client or CentralogClient()
|
|
30
|
+
|
|
31
|
+
async def _report(request: Request, exc: BaseException) -> None:
|
|
32
|
+
route = request.scope.get("route")
|
|
33
|
+
client.capture(
|
|
34
|
+
exc,
|
|
35
|
+
request={
|
|
36
|
+
"method": request.method,
|
|
37
|
+
"url": str(request.url),
|
|
38
|
+
"route": getattr(route, "name", None) or getattr(route, "path", None),
|
|
39
|
+
},
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
async def _handle_500(request: Request, exc: Exception) -> Any:
|
|
43
|
+
await _report(request, exc)
|
|
44
|
+
return JSONResponse({"detail": "Internal Server Error"}, status_code=500)
|
|
45
|
+
|
|
46
|
+
async def _handle_http(request: Request, exc: Any) -> Any:
|
|
47
|
+
from fastapi import HTTPException
|
|
48
|
+
|
|
49
|
+
if isinstance(exc, HTTPException) and exc.status_code >= 500:
|
|
50
|
+
await _report(request, exc)
|
|
51
|
+
raise exc
|
|
52
|
+
|
|
53
|
+
app.add_exception_handler(Exception, _handle_500)
|
|
54
|
+
if capture_http_exceptions:
|
|
55
|
+
from fastapi import HTTPException
|
|
56
|
+
|
|
57
|
+
app.add_exception_handler(HTTPException, _handle_http)
|
|
58
|
+
|
|
59
|
+
return client
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Flask integration: register an error handler that reports 500s."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from flask import Flask, Response, request
|
|
7
|
+
from werkzeug.exceptions import HTTPException
|
|
8
|
+
except ImportError: # pragma: no cover
|
|
9
|
+
Flask = None # type: ignore[assignment]
|
|
10
|
+
Response = None # type: ignore[assignment]
|
|
11
|
+
request = None # type: ignore[assignment]
|
|
12
|
+
HTTPException = Exception # type: ignore[assignment,misc]
|
|
13
|
+
|
|
14
|
+
from ..client import CentralogClient
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def register(app: Flask, client: CentralogClient | None = None) -> CentralogClient:
|
|
18
|
+
"""Register Centralog error reporting on a Flask app.
|
|
19
|
+
|
|
20
|
+
Captures unhandled 500s. Your error responses stay unchanged.
|
|
21
|
+
"""
|
|
22
|
+
client = client or CentralogClient()
|
|
23
|
+
|
|
24
|
+
@app.errorhandler(Exception)
|
|
25
|
+
def _report(error: BaseException): # type: ignore[no-untyped-def]
|
|
26
|
+
if isinstance(error, HTTPException) and getattr(error, "code", 500) < 500:
|
|
27
|
+
return error.get_response()
|
|
28
|
+
client.capture(
|
|
29
|
+
error,
|
|
30
|
+
request={
|
|
31
|
+
"method": request.method,
|
|
32
|
+
"url": request.url,
|
|
33
|
+
"route": request.url_rule.endpoint if request.url_rule else None,
|
|
34
|
+
},
|
|
35
|
+
)
|
|
36
|
+
return Response("Internal Server Error", status=500)
|
|
37
|
+
|
|
38
|
+
return client
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Build ingest payloads matching the Centralog Fase 8 contract."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import traceback
|
|
6
|
+
import uuid
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def build_payload(
|
|
11
|
+
exception: BaseException,
|
|
12
|
+
environment: str,
|
|
13
|
+
release: str | None = None,
|
|
14
|
+
level: str = "error",
|
|
15
|
+
context: dict[str, Any] | None = None,
|
|
16
|
+
request: dict[str, Any] | None = None,
|
|
17
|
+
user: dict[str, Any] | None = None,
|
|
18
|
+
) -> dict[str, Any]:
|
|
19
|
+
"""Build an ingest payload from an exception and optional context.
|
|
20
|
+
|
|
21
|
+
Mirrors the Laravel SDK PayloadBuilder output exactly.
|
|
22
|
+
"""
|
|
23
|
+
tb = exception.__traceback__
|
|
24
|
+
# Walk to the deepest user frame for file/line, like Laravel reports throw site.
|
|
25
|
+
deepest: dict[str, Any] = {"file": "<unknown>", "line": 0}
|
|
26
|
+
if tb is not None:
|
|
27
|
+
frames = traceback.extract_tb(tb)
|
|
28
|
+
if frames:
|
|
29
|
+
last = frames[-1]
|
|
30
|
+
deepest = {"file": last.filename, "line": last.lineno or 0}
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
"event_id": str(uuid.uuid4()),
|
|
34
|
+
"environment": environment,
|
|
35
|
+
"release": release,
|
|
36
|
+
"level": level,
|
|
37
|
+
"exception": {
|
|
38
|
+
"class": f"{type(exception).__module__}.{type(exception).__name__}",
|
|
39
|
+
"message": str(exception) or type(exception).__name__,
|
|
40
|
+
"file": deepest["file"],
|
|
41
|
+
"line": deepest["line"],
|
|
42
|
+
"trace": "".join(traceback.format_exception(exception)),
|
|
43
|
+
},
|
|
44
|
+
"request": request,
|
|
45
|
+
"user": user,
|
|
46
|
+
"context": context if context else None,
|
|
47
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "centralog-sdk"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Python SDK for Centralog error monitoring. Captures exceptions and sends a copy to your Centralog platform without breaking your app."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = { text = "MIT" }
|
|
8
|
+
keywords = ["centralog", "error-monitoring", "fastapi", "flask", "django"]
|
|
9
|
+
dependencies = [
|
|
10
|
+
"httpx>=0.27",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
fastapi = ["fastapi>=0.110"]
|
|
15
|
+
flask = ["flask>=3.0"]
|
|
16
|
+
django = ["django>=4.2"]
|
|
17
|
+
dev = ["pytest>=8.0", "pytest-asyncio>=0.23", "ruff>=0.4", "fastapi>=0.110", "flask>=3.0", "django>=4.2", "httpx>=0.27"]
|
|
18
|
+
|
|
19
|
+
[build-system]
|
|
20
|
+
requires = ["hatchling"]
|
|
21
|
+
build-backend = "hatchling.build"
|
|
22
|
+
|
|
23
|
+
[tool.hatch.build.targets.wheel]
|
|
24
|
+
packages = ["centralog"]
|
|
25
|
+
|
|
26
|
+
[tool.pytest.ini_options]
|
|
27
|
+
testpaths = ["tests"]
|
|
28
|
+
|
|
29
|
+
[tool.ruff]
|
|
30
|
+
line-length = 100
|
|
31
|
+
target-version = "py310"
|