feat(clients): add Python, Go, and Java client libraries (BIT-14250)
Zero-dependency clients for errors.bitreport.pt following the same patterns as clients/node and clients/php: batch size 25, 5 s flush interval, 8 s HTTP timeout, fire-and-forget, env-var config. Each client ships with unit tests backed by an embedded HTTP server (no mocks), an example file, and a build manifest (pyproject.toml, go.mod, pom.xml). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
1 parent
8bb49ce32b
commit
da57d2a444
12 files changed
+1653
No files matched your search
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
BitReport Error Reporter — Python client for errors.bitreport.pt ingest API.
|
||||
|
||||
Drop this file into any Python 3.8+ project. Zero dependencies (uses urllib).
|
||||
|
||||
Usage:
|
||||
from error_reporter import init_reporter, report_error, report_message, flush
|
||||
init_reporter(token=os.environ['ERROR_REPORTING_TOKEN'])
|
||||
|
||||
try:
|
||||
risky_operation()
|
||||
except Exception as e:
|
||||
report_error(e, {'url': '/api/foo'})
|
||||
|
||||
Environment variables:
|
||||
ERROR_REPORTING_TOKEN — ingest API key (required)
|
||||
ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
|
||||
ERROR_REPORTING_DISABLED — set to "1" to disable
|
||||
ERROR_REPORTING_PROJECT_NAME — display name in ingest context (optional)
|
||||
ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
|
||||
ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import traceback
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
_token: str = ""
|
||||
_endpoint: str = "https://errors.bitreport.pt"
|
||||
_disabled: bool = False
|
||||
_project_name: str = os.environ.get("ERROR_REPORTING_PROJECT_NAME", "")
|
||||
_project_slug: str = os.environ.get("ERROR_REPORTING_PROJECT_SLUG", "")
|
||||
_gitea_repo: str = os.environ.get("ERROR_REPORTING_GITEA_REPO", "")
|
||||
|
||||
_queue: List[Dict[str, Any]] = []
|
||||
_lock = threading.Lock()
|
||||
_flush_timer: Optional[threading.Timer] = None
|
||||
|
||||
BATCH_SIZE = 25
|
||||
FLUSH_SECS = 5.0
|
||||
TIMEOUT_SECS = 8.0
|
||||
|
||||
|
||||
def init_reporter(
|
||||
token: str = "",
|
||||
endpoint: str = "",
|
||||
disabled: Optional[bool] = None,
|
||||
project_name: str = "",
|
||||
project_slug: str = "",
|
||||
gitea_repo: str = "",
|
||||
) -> None:
|
||||
"""Initialise the reporter. Call once at startup."""
|
||||
global _token, _endpoint, _disabled, _project_name, _project_slug, _gitea_repo
|
||||
|
||||
_token = token or os.environ.get("ERROR_REPORTING_TOKEN", "")
|
||||
_endpoint = (
|
||||
endpoint
|
||||
or os.environ.get("ERROR_REPORTING_ENDPOINT", "")
|
||||
or "https://errors.bitreport.pt"
|
||||
).rstrip("/")
|
||||
_disabled = disabled if disabled is not None else os.environ.get("ERROR_REPORTING_DISABLED") == "1"
|
||||
_project_name = project_name or os.environ.get("ERROR_REPORTING_PROJECT_NAME", "") or _project_name
|
||||
_project_slug = project_slug or os.environ.get("ERROR_REPORTING_PROJECT_SLUG", "") or _project_slug
|
||||
_gitea_repo = gitea_repo or os.environ.get("ERROR_REPORTING_GITEA_REPO", "") or _gitea_repo
|
||||
|
||||
if not _disabled and _token:
|
||||
_orig_excepthook = sys.excepthook
|
||||
|
||||
def _excepthook(exc_type, exc_value, exc_tb):
|
||||
report_error(exc_value, {"uncaught": True})
|
||||
_orig_excepthook(exc_type, exc_value, exc_tb)
|
||||
|
||||
sys.excepthook = _excepthook
|
||||
|
||||
|
||||
def report_error(exc: BaseException, context: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""Report an exception with an optional extra context dict."""
|
||||
if _disabled or not _token:
|
||||
return
|
||||
if context is None:
|
||||
context = {}
|
||||
|
||||
tb_lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
|
||||
stack = "".join(tb_lines).strip()
|
||||
|
||||
file_path = ""
|
||||
line_number: Optional[int] = None
|
||||
if exc.__traceback__:
|
||||
tb = exc.__traceback__
|
||||
while tb.tb_next:
|
||||
tb = tb.tb_next
|
||||
file_path = tb.tb_frame.f_code.co_filename
|
||||
line_number = tb.tb_lineno
|
||||
|
||||
ctx: Dict[str, Any] = {"error_type": type(exc).__name__}
|
||||
if file_path:
|
||||
ctx["file_path"] = file_path
|
||||
if line_number is not None:
|
||||
ctx["line_number"] = line_number
|
||||
if _project_name:
|
||||
ctx["project_name"] = _project_name
|
||||
if _project_slug:
|
||||
ctx["project_slug"] = _project_slug
|
||||
if _gitea_repo:
|
||||
ctx["gitea_repo"] = _gitea_repo
|
||||
ctx.update(context)
|
||||
|
||||
_enqueue({
|
||||
"schema_version": 1,
|
||||
"occurred_at": _now_iso(),
|
||||
"level": "error",
|
||||
"message": str(exc),
|
||||
"stacktrace": stack,
|
||||
"context": ctx,
|
||||
})
|
||||
|
||||
|
||||
def report_message(
|
||||
message: str,
|
||||
level: str = "error",
|
||||
context: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""Report a plain message (warning, info, etc.)."""
|
||||
if _disabled or not _token:
|
||||
return
|
||||
if context is None:
|
||||
context = {}
|
||||
|
||||
ctx: Dict[str, Any] = {}
|
||||
if _project_name:
|
||||
ctx["project_name"] = _project_name
|
||||
if _project_slug:
|
||||
ctx["project_slug"] = _project_slug
|
||||
if _gitea_repo:
|
||||
ctx["gitea_repo"] = _gitea_repo
|
||||
ctx.update(context)
|
||||
|
||||
event: Dict[str, Any] = {
|
||||
"schema_version": 1,
|
||||
"occurred_at": _now_iso(),
|
||||
"level": level,
|
||||
"message": message,
|
||||
}
|
||||
if ctx:
|
||||
event["context"] = ctx
|
||||
_enqueue(event)
|
||||
|
||||
|
||||
def flush() -> None:
|
||||
"""Flush all queued events synchronously. Call before process exit."""
|
||||
global _flush_timer
|
||||
with _lock:
|
||||
if _flush_timer is not None:
|
||||
_flush_timer.cancel()
|
||||
_flush_timer = None
|
||||
to_send = list(_queue)
|
||||
del _queue[:]
|
||||
|
||||
for i in range(0, max(len(to_send), 1), BATCH_SIZE):
|
||||
batch = to_send[i : i + BATCH_SIZE]
|
||||
if batch:
|
||||
_send(batch)
|
||||
|
||||
|
||||
# --- internals ---
|
||||
|
||||
def _now_iso() -> str:
|
||||
now = datetime.now(timezone.utc)
|
||||
return now.strftime(f"%Y-%m-%dT%H:%M:%S.{now.microsecond // 1000:03d}Z")
|
||||
|
||||
|
||||
def _enqueue(event: Dict[str, Any]) -> None:
|
||||
global _flush_timer
|
||||
batch_to_send: Optional[List[Dict[str, Any]]] = None
|
||||
|
||||
with _lock:
|
||||
_queue.append(event)
|
||||
if len(_queue) >= BATCH_SIZE:
|
||||
batch_to_send = _queue[:BATCH_SIZE]
|
||||
del _queue[:BATCH_SIZE]
|
||||
elif _flush_timer is None:
|
||||
_flush_timer = threading.Timer(FLUSH_SECS, _flush_timer_cb)
|
||||
_flush_timer.daemon = True
|
||||
_flush_timer.start()
|
||||
|
||||
if batch_to_send is not None:
|
||||
threading.Thread(target=_send, args=(batch_to_send,), daemon=True).start()
|
||||
|
||||
|
||||
def _flush_timer_cb() -> None:
|
||||
global _flush_timer
|
||||
with _lock:
|
||||
_flush_timer = None
|
||||
if not _queue:
|
||||
return
|
||||
batch = _queue[:BATCH_SIZE]
|
||||
del _queue[:BATCH_SIZE]
|
||||
if batch:
|
||||
threading.Thread(target=_send, args=(batch,), daemon=True).start()
|
||||
|
||||
|
||||
def _send(events: List[Dict[str, Any]]) -> None:
|
||||
if not events:
|
||||
return
|
||||
try:
|
||||
payload = json.dumps({"events": events}).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
f"{_endpoint}/v1/ingest/events",
|
||||
data=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {_token}",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
urllib.request.urlopen(req, timeout=TIMEOUT_SECS)
|
||||
except Exception:
|
||||
pass # fire-and-forget: never crash the host app
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
Basic usage example for the BitReport Python error reporter.
|
||||
|
||||
Run with:
|
||||
ERROR_REPORTING_TOKEN=your_token python basic_usage.py
|
||||
"""
|
||||
|
||||
import atexit
|
||||
import os
|
||||
|
||||
from error_reporter import flush, init_reporter, report_error, report_message
|
||||
|
||||
init_reporter(
|
||||
token=os.environ.get("ERROR_REPORTING_TOKEN", ""),
|
||||
project_name="My Python App",
|
||||
project_slug="my-python-app",
|
||||
)
|
||||
|
||||
# Flush before the process exits so queued events are not lost
|
||||
atexit.register(flush)
|
||||
|
||||
# Report a plain message
|
||||
report_message("Application started", level="info")
|
||||
|
||||
# Report a warning with extra context
|
||||
report_message("Cache miss", level="warning", context={"cache_key": "user:42"})
|
||||
|
||||
# Report an exception caught in a try/except
|
||||
try:
|
||||
result = 1 / 0
|
||||
except ZeroDivisionError as e:
|
||||
report_error(e, {"operation": "divide", "numerator": 1, "denominator": 0})
|
||||
|
||||
# Flush immediately so the example does not exit before events are sent
|
||||
flush()
|
||||
print("Events sent. Check your errors.bitreport.pt dashboard.")
|
||||
@@ -0,0 +1,32 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.backends.legacy:build"
|
||||
|
||||
[project]
|
||||
name = "bitreport-errors"
|
||||
version = "1.0.0"
|
||||
description = "Lightweight error reporting client for errors.bitreport.pt"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
license = { text = "MIT" }
|
||||
keywords = ["error-reporting", "monitoring", "bitreport"]
|
||||
classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Topic :: System :: Monitoring",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://errors.bitreport.pt"
|
||||
|
||||
[tool.setuptools]
|
||||
py-modules = ["error_reporter"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Unit tests for error_reporter.py — uses an embedded HTTP server, no mocks."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import error_reporter as er
|
||||
|
||||
|
||||
class _CapturingHandler(BaseHTTPRequestHandler):
|
||||
bodies: list = []
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(length)
|
||||
_CapturingHandler.bodies.append(json.loads(body))
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
|
||||
class TestErrorReporter(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.server = HTTPServer(("127.0.0.1", 0), _CapturingHandler)
|
||||
cls.server_thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.server_thread.start()
|
||||
cls.port = cls.server.server_address[1]
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.shutdown()
|
||||
|
||||
def setUp(self):
|
||||
_CapturingHandler.bodies = []
|
||||
er._token = "test-token"
|
||||
er._endpoint = f"http://127.0.0.1:{self.port}"
|
||||
er._disabled = False
|
||||
er._project_name = ""
|
||||
er._project_slug = ""
|
||||
er._gitea_repo = ""
|
||||
with er._lock:
|
||||
er._queue.clear()
|
||||
if er._flush_timer is not None:
|
||||
er._flush_timer.cancel()
|
||||
er._flush_timer = None
|
||||
|
||||
# --- report_error ---
|
||||
|
||||
def test_report_error_sends_event(self):
|
||||
try:
|
||||
raise ValueError("boom")
|
||||
except ValueError as exc:
|
||||
er.report_error(exc)
|
||||
er.flush()
|
||||
|
||||
self.assertEqual(len(_CapturingHandler.bodies), 1)
|
||||
events = _CapturingHandler.bodies[0]["events"]
|
||||
self.assertEqual(len(events), 1)
|
||||
ev = events[0]
|
||||
self.assertEqual(ev["schema_version"], 1)
|
||||
self.assertEqual(ev["level"], "error")
|
||||
self.assertEqual(ev["message"], "boom")
|
||||
self.assertIn("stacktrace", ev)
|
||||
self.assertEqual(ev["context"]["error_type"], "ValueError")
|
||||
|
||||
def test_report_error_extracts_file_line(self):
|
||||
try:
|
||||
raise RuntimeError("loc test")
|
||||
except RuntimeError as exc:
|
||||
er.report_error(exc)
|
||||
er.flush()
|
||||
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
|
||||
self.assertIn("file_path", ctx)
|
||||
self.assertIn("line_number", ctx)
|
||||
self.assertIsInstance(ctx["line_number"], int)
|
||||
|
||||
def test_report_error_with_extra_context(self):
|
||||
try:
|
||||
raise KeyError("key")
|
||||
except KeyError as exc:
|
||||
er.report_error(exc, {"request_id": "abc123"})
|
||||
er.flush()
|
||||
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
|
||||
self.assertEqual(ctx["request_id"], "abc123")
|
||||
|
||||
# --- report_message ---
|
||||
|
||||
def test_report_message_default_level(self):
|
||||
er.report_message("something bad")
|
||||
er.flush()
|
||||
ev = _CapturingHandler.bodies[0]["events"][0]
|
||||
self.assertEqual(ev["level"], "error")
|
||||
self.assertEqual(ev["message"], "something bad")
|
||||
|
||||
def test_report_message_warning(self):
|
||||
er.report_message("heads up", "warning", {"foo": "bar"})
|
||||
er.flush()
|
||||
ev = _CapturingHandler.bodies[0]["events"][0]
|
||||
self.assertEqual(ev["level"], "warning")
|
||||
self.assertEqual(ev["context"]["foo"], "bar")
|
||||
|
||||
# --- project context ---
|
||||
|
||||
def test_project_fields_added(self):
|
||||
er._project_name = "My App"
|
||||
er._project_slug = "my-app"
|
||||
er._gitea_repo = "org/my-app"
|
||||
er.report_message("test")
|
||||
er.flush()
|
||||
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
|
||||
self.assertEqual(ctx["project_name"], "My App")
|
||||
self.assertEqual(ctx["project_slug"], "my-app")
|
||||
self.assertEqual(ctx["gitea_repo"], "org/my-app")
|
||||
|
||||
# --- disabled / no token ---
|
||||
|
||||
def test_disabled_skips(self):
|
||||
er._disabled = True
|
||||
er.report_message("nope")
|
||||
er.flush()
|
||||
self.assertEqual(len(_CapturingHandler.bodies), 0)
|
||||
|
||||
def test_no_token_skips(self):
|
||||
er._token = ""
|
||||
er.report_message("nope")
|
||||
er.flush()
|
||||
self.assertEqual(len(_CapturingHandler.bodies), 0)
|
||||
|
||||
# --- batching ---
|
||||
|
||||
def test_batch_flushed_on_size(self):
|
||||
for i in range(25):
|
||||
er.report_message(f"msg {i}")
|
||||
time.sleep(0.2) # allow background send thread to complete
|
||||
self.assertGreaterEqual(len(_CapturingHandler.bodies), 1)
|
||||
total_events = sum(len(b["events"]) for b in _CapturingHandler.bodies)
|
||||
self.assertEqual(total_events, 25)
|
||||
|
||||
def test_authorization_header(self):
|
||||
# Capture headers by extending the server handler temporarily
|
||||
captured_headers = {}
|
||||
|
||||
class HeaderHandler(_CapturingHandler):
|
||||
def do_POST(self):
|
||||
captured_headers["auth"] = self.headers.get("Authorization")
|
||||
super().do_POST()
|
||||
|
||||
self.server.RequestHandlerClass = HeaderHandler
|
||||
try:
|
||||
er.report_message("check auth")
|
||||
er.flush()
|
||||
finally:
|
||||
self.server.RequestHandlerClass = _CapturingHandler
|
||||
|
||||
self.assertEqual(captured_headers.get("auth"), "Bearer test-token")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user