""" 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