Python SDK
DebugBundle Python SDK for Django, Flask, FastAPI, and stdlib.
The Python SDK is live on PyPI as debugbundle-python and follows the same universal capture, redaction, probe, and 5xx request-failure rules as the other shipped DebugBundle SDKs.
Current release: 3.0.0. Before upgrading across major versions, review the version 3.0 guidance for capture, callback and delivery timing.
Installation
pip install debugbundle-pythonInitialize
Initialize once at application startup with DEBUGBUNDLE_PROJECT_TOKEN set in the server environment. Initialization installs the exception hooks. Add logging and framework adapters in Integrations.
import os
import debugbundle
debugbundle.init(
project_token=os.environ["DEBUGBUNDLE_PROJECT_TOKEN"],
environment="production",
service="api",
)Integrations
Django, Flask, FastAPI, Python logging, structlog, loguru and browser relay helpers are supported.
Vanilla Hooks
The Python SDK provides opt-in hooks for automatic capture:
import debugbundle
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_PROJECT_TOKEN"])
# Capture unhandled exceptions via sys.excepthook
debugbundle.capture_exceptions()
# Capture Python logging → DebugBundle events
debugbundle.capture_logging()
# Capture asyncio loop exception handler
debugbundle.capture_async()Each hook is independently enabled. All three can run together.
Framework Integrations
Django
# settings.py
MIDDLEWARE = [
"debugbundle.integrations.django.DebugBundleMiddleware",
# ... other middleware
]
DEBUGBUNDLE = {
"project_token": os.environ["DEBUGBUNDLE_PROJECT_TOKEN"],
"service": "django-api",
}The middleware captures unhandled exceptions and attaches request context (method, path, status code, headers) automatically.
Flask
from flask import Flask
import debugbundle
from debugbundle.integrations.flask import init_flask
app = Flask(__name__)
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_PROJECT_TOKEN"])
init_flask(app)init_flask registers an errorhandler(Exception) and a before_request hook for request context capture.
FastAPI
from fastapi import FastAPI
import debugbundle
from debugbundle.integrations.fastapi import DebugBundleMiddleware
app = FastAPI()
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_PROJECT_TOKEN"])
app.add_middleware(DebugBundleMiddleware)The ASGI middleware captures exceptions and request/response data. Works with Starlette-based frameworks.
Browser Relay
The Python SDK includes a full browser relay handler for Django, Flask, and FastAPI applications that also load @debugbundle/sdk-browser.
debugbundle.BrowserRelayHandlerexposes the framework-agnostic core handler.debugbundle.create_django_relay_view(...)returns a Django view forPOST /debugbundle/browser.debugbundle.create_flask_relay_handler(...)registers the relay route on a Flask app.debugbundle.create_fastapi_relay_handler(...)registers the relay route on a FastAPI app.
import os
from debugbundle.integrations import create_flask_relay_handler
register_relay = create_flask_relay_handler(
allowed_origins=["https://app.example.com"],
project_mode="connected",
project_token=os.environ["DEBUGBUNDLE_PROJECT_TOKEN"],
endpoint="https://api.debugbundle.com/v1/events",
)
register_relay(app)The relay handler validates same-origin or configured allowed origins, requires Content-Type: application/json, accepts the canonical batch request shape, rejects bodies larger than 256 KB, applies per-IP rate limiting, strips trust-sensitive headers and fields, forces sdk_name to @debugbundle/sdk-browser, and preserves browser correlation fields (request_id, trace_id, session_id, and user_id_hash) when they are strings or null.
Delivery modes match the other shipped server SDKs:
project_mode="local-only"writes accepted browser events to.debugbundle/local/events/.project_mode="connected"with the defaultdurable_write=Truewrites a durable relay spool record and then forwards with the server-side project token.project_mode="connected"withdurable_write=Falseuses the lower-latency forward-only path.
Logger Integrations
Call capture_logging() after initialization to attach stdlib logging and detect installed structlog/loguru integrations:
import os
import logging
import debugbundle
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_PROJECT_TOKEN"])
logger = logging.getLogger("checkout")
logger.setLevel(logging.ERROR)
debugbundle.capture_logging(logger)
logger.error("Payment failed")For structlog, configure your normal processors and obtain loggers after capture_logging(). No DebugBundle processor needs to be inserted. Native level filters and processors that raise structlog.DropEvent run before capture. Stdlib-backed loggers also respect disabled state, logger filters and logging.disable().
Loguru is detected automatically when installed. Filters and levels on other Loguru sinks are destination-specific; use the SDK log_level setting or before_send to control its capture.
First-event verification
Use an explicit setup event in a development or staging application, then confirm the matching service and environment in a received event or incident. Initialization, a healthy status and an empty queue are not delivery receipts. Keep the application running long enough for delivery; use bounded flushing only in tests or controlled teardown, never in a request handler.
debugbundle.capture_message("DebugBundle setup check", level="error")For connected delivery, confirm the event in DebugBundle and inspect its incident with the CLI. For local-only browser relay files, run debugbundle process and debugbundle inspect <incident-id> in the backend repository. A local file or mock endpoint receipt proves only that destination; it does not prove cloud acceptance.
Configuration
The built-in application client uses HTTP in every environment. A literal local token does not select file transport. Browser relay local-only files are a separate delivery path; use a real ingestion token and endpoint for backend capture.
| Option | Type | Default | Description |
|---|---|---|---|
project_token | str | — | Required. Project token for ingestion auth (dbundle_proj_...). |
environment | str | development | production, staging, development, etc. |
service | str | python-service | Service name for multi-service projects. |
enabled | bool | True | Kill switch — set to False to disable all capture. |
redact_fields | list[str] | Default set | Additional field names to redact before transmission. |
sample_rate | float | 1.0 | Event sampling rate (0.0–1.0). |
batch_size | int | 25 | Max events per batch. |
flush_interval | float | 5.0 | Background flush interval in seconds. |
endpoint | str | https://api.debugbundle.com/v1/events | Ingestion endpoint URL. |
before_send | Callable | None | Application-owned event hook; return a valid replacement to keep it or None to drop it. |
on_diagnostic | Callable | None | Optional local diagnostic callback, invoked asynchronously on one bounded daemon lane outside SDK locks. |
Optional diagnostic output is independent of event delivery: flush() does not wait for on_diagnostic. A stalled callback keeps its existing lane; queued diagnostics are cleared on disposal/reinitialisation and an already running callback may finish. Callback code has a synchronous return contract. See internal diagnostics and hook size limits.
Capture Methods
import debugbundle
# Capture an exception with optional context
try:
riskyOperation()
except Exception as e:
debugbundle.capture_exception(e, {"user_id": "usr_123"})
# Capture a structured log event
debugbundle.capture_log("Payment processing failed", "error", {
"order_id": "ord_456",
"amount": 99.99,
})
# Capture HTTP request/response pair
debugbundle.capture_request(request, response, {"route": "/api/orders"})
# Capture a diagnostic message
debugbundle.capture_message("Deployment started", "info")
# Set persistent context for all future events
debugbundle.set_context("deployment", {"version": "1.4.2"})
# Probe — diagnostic ring buffer
debugbundle.probe("db_pool", lambda: {"active": pool.active, "idle": pool.idle})
# During controlled teardown or tests only; verify receipt separately
debugbundle.flush()Transport
The built-in application client sends through HTTP to the configured ingestion endpoint. It does not read connection.json to select file delivery and its init API has no transport or local_events_dir option. The browser relay separately supports local-only files and connected durable spooling; see Browser Relay.
Volume Control
The Python SDK implements the same volume controls as all DebugBundle SDKs:
- Duplicate suppression — First 3 identical events in a 30-second window sent normally; subsequent duplicates aggregated into a single
error_suppressedevent. - Loop protection — More than 10 identical errors in 2 seconds forces suppression. Checkpoint every 30 seconds. Resets after 60 seconds of silence.
- Bounded retention — Delivery is best effort; queue pressure, shutdown and retry limits can lose events. Retryable responses respect bounded
Retry-Afterhints.
Next Steps
- Universal SDK Interface — Full interface contract across all SDKs
- Browser Relay Setup — Shared browser relay contract and deployment guidance
- CLI Local Workflow — Process captured events locally
- API Ingestion — Direct event ingestion API