@error-reporting/python 0.0.0-stage → 0.1.0
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.
- package/README.md +20 -2
- package/error_reporting/__init__.py +97 -0
- package/package.json +16 -4
- package/pyproject.toml +12 -0
package/README.md
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @error-reporting/python
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
需要 Python 3.9 或以上。在 Python 虚拟环境中安装 npm 包内的 Python 源码。
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @error-reporting/python
|
|
7
|
+
python -m pip install ./node_modules/@error-reporting/python
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from error_reporting import Init, CaptureException
|
|
12
|
+
|
|
13
|
+
Init({"dsn": dsn, "environment": "production", "release": "git-sha"})
|
|
14
|
+
|
|
15
|
+
# 在 except 块里补报已处理的异常。
|
|
16
|
+
CaptureException(error, {"requestId": "request-42"})
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`Init()` 也可从 `ERROR_REPORTING_DSN`、`ERROR_REPORTING_ENVIRONMENT` 和 `ERROR_REPORTING_RELEASE` 读取配置,
|
|
20
|
+
并接入 Python 主线程和 `threading.Thread` 的未捕获异常钩子。被框架接住的异常请在框架错误处理器中调用 `CaptureException`。
|
|
21
|
+
同步上报成功返回事件 ID,失败返回 `None`。
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Send Python exceptions to the Error Reporting Platform."""
|
|
2
|
+
|
|
3
|
+
import http.client
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
import traceback
|
|
11
|
+
import uuid
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
__all__ = ["Init", "CaptureException"]
|
|
15
|
+
|
|
16
|
+
_config = None
|
|
17
|
+
_lock = threading.Lock()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def Init(options=None):
|
|
21
|
+
"""Configure the SDK once and chain the existing uncaught exception hooks."""
|
|
22
|
+
global _config
|
|
23
|
+
options = {} if options is None else options
|
|
24
|
+
dsn = options.get("dsn") or os.getenv("ERROR_REPORTING_DSN", "")
|
|
25
|
+
try:
|
|
26
|
+
url = urlsplit(dsn.strip())
|
|
27
|
+
port = url.port
|
|
28
|
+
if (url.scheme not in ("http", "https") or not url.hostname
|
|
29
|
+
or not re.fullmatch(r"[a-zA-Z0-9]+", url.username or "")
|
|
30
|
+
or url.password is not None or not re.fullmatch(r"/\d{1,24}/?", url.path, re.ASCII)
|
|
31
|
+
or "?" in dsn or "#" in dsn):
|
|
32
|
+
raise ValueError
|
|
33
|
+
except (ValueError, AttributeError):
|
|
34
|
+
raise ValueError("invalid error reporting DSN") from None
|
|
35
|
+
|
|
36
|
+
with _lock:
|
|
37
|
+
if _config is not None:
|
|
38
|
+
raise RuntimeError("error reporting is already initialized")
|
|
39
|
+
_config = (
|
|
40
|
+
url.scheme, url.hostname, port, "/api/" + url.path.strip("/") + "/envelope/", url.username,
|
|
41
|
+
options.get("environment") or os.getenv("ERROR_REPORTING_ENVIRONMENT") or "development",
|
|
42
|
+
options.get("release") or os.getenv("ERROR_REPORTING_RELEASE", ""),
|
|
43
|
+
)
|
|
44
|
+
previous_main, previous_thread = sys.excepthook, threading.excepthook
|
|
45
|
+
|
|
46
|
+
def on_main(kind, error, trace):
|
|
47
|
+
"""Report an unhandled exception before handing it to the original hook."""
|
|
48
|
+
if isinstance(error, Exception):
|
|
49
|
+
CaptureException(error)
|
|
50
|
+
previous_main(kind, error, trace)
|
|
51
|
+
|
|
52
|
+
def on_thread(args):
|
|
53
|
+
"""Report worker exceptions while preserving the existing thread hook."""
|
|
54
|
+
if isinstance(args.exc_value, Exception):
|
|
55
|
+
CaptureException(args.exc_value)
|
|
56
|
+
previous_thread(args)
|
|
57
|
+
|
|
58
|
+
sys.excepthook = on_main
|
|
59
|
+
threading.excepthook = on_thread
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def CaptureException(error, context=None):
|
|
63
|
+
"""Send an exception and return its event ID, or None on failure."""
|
|
64
|
+
config = _config
|
|
65
|
+
if config is None or not isinstance(error, BaseException):
|
|
66
|
+
return None
|
|
67
|
+
scheme, host, port, endpoint, key, environment, release = config
|
|
68
|
+
connection = None
|
|
69
|
+
try:
|
|
70
|
+
event_id = uuid.uuid4().hex
|
|
71
|
+
request_id = (context or {}).get("requestId")
|
|
72
|
+
frames = traceback.extract_tb(error.__traceback__)[-50:]
|
|
73
|
+
event = {
|
|
74
|
+
"event_id": event_id, "timestamp": time.time(), "platform": "python",
|
|
75
|
+
"environment": environment[:80], "release": release[:160],
|
|
76
|
+
"tags": {"request_id": request_id[:128]} if request_id else {},
|
|
77
|
+
"exception": {"values": [{
|
|
78
|
+
"type": type(error).__name__[:120], "value": str(error)[:2000],
|
|
79
|
+
"stacktrace": {"frames": [
|
|
80
|
+
{"filename": f.filename[:500], "function": f.name[:180], "lineno": f.lineno} for f in frames
|
|
81
|
+
]},
|
|
82
|
+
}]},
|
|
83
|
+
}
|
|
84
|
+
body = ("\n".join(map(json.dumps, ({"event_id": event_id}, {"type": "event"}, event))) + "\n").encode("utf-8")
|
|
85
|
+
cls = http.client.HTTPSConnection if scheme == "https" else http.client.HTTPConnection
|
|
86
|
+
connection = cls(host, port, timeout=2)
|
|
87
|
+
connection.request("POST", endpoint, body, {
|
|
88
|
+
"Content-Type": "application/x-sentry-envelope",
|
|
89
|
+
"X-Sentry-Auth": "Sentry sentry_version=7, sentry_key=" + key,
|
|
90
|
+
})
|
|
91
|
+
with connection.getresponse() as response:
|
|
92
|
+
return event_id if 200 <= response.status < 300 else None
|
|
93
|
+
except (OSError, http.client.HTTPException, ValueError, TypeError):
|
|
94
|
+
return None
|
|
95
|
+
finally:
|
|
96
|
+
if connection is not None:
|
|
97
|
+
connection.close()
|
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@error-reporting/python",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Error Reporting Platform SDK for Python",
|
|
5
|
+
"files": [
|
|
6
|
+
"error_reporting/__init__.py",
|
|
7
|
+
"pyproject.toml"
|
|
8
|
+
],
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public",
|
|
11
|
+
"registry": "https://registry.npmjs.org/"
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://gitee.com/qglove/error-reporting-platform.git",
|
|
16
|
+
"directory": "packages/native/python"
|
|
17
|
+
}
|
|
18
|
+
}
|
package/pyproject.toml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "error-reporting-sdk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
requires-python = ">=3.9"
|
|
9
|
+
description = "Error Reporting Platform SDK for Python"
|
|
10
|
+
|
|
11
|
+
[tool.setuptools.packages.find]
|
|
12
|
+
include = ["error_reporting"]
|