DebugBundle
SDKs

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.

Installation

pip install debugbundle-python

Initialize

import os
import debugbundle

debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])

Configuration

OptionTypeDefaultDescription
project_tokenstrRequired. Project token for ingestion auth (dbundle_proj_...).
environmentstrauto-detectproduction, staging, development, etc.
servicestrauto-detectService name for multi-service projects.
enabledboolTrueKill switch — set to False to disable all capture.
redact_fieldslist[str]Default setAdditional field names to redact before transmission.
sample_ratefloat1.0Event sampling rate (0.0–1.0).
batch_sizeint50Max events per batch.
flush_intervalint2000Max milliseconds before batch send.
endpointstrhttps://api.debugbundle.com/v1/eventsIngestion endpoint URL.
transportstrhttphttp or file (local-only mode).
local_events_dirstr.debugbundle/local/eventsDirectory for file transport output.

Vanilla Hooks

The Python SDK provides opt-in hooks for automatic capture:

import debugbundle

debugbundle.init(project_token=os.environ["DEBUGBUNDLE_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_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_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_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.BrowserRelayHandler exposes the framework-agnostic core handler.
  • debugbundle.create_django_relay_view(...) returns a Django view for POST /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_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 default durable_write=True writes a durable relay spool record and then forwards with the server-side project token.
  • project_mode="connected" with durable_write=False uses the lower-latency forward-only path.

Logger Integrations

stdlib logging

import logging
import debugbundle

debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])

handler = debugbundle.LoggingHandler(level=logging.ERROR)
logging.getLogger().addHandler(handler)

structlog

import structlog
import debugbundle

debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])

structlog.configure(
    processors=[
        # ... other processors
        debugbundle.integrations.structlog.debugbundle_processor,
        structlog.dev.ConsoleRenderer(),
    ]
)

loguru

from loguru import logger
import debugbundle

debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])

logger.add(debugbundle.integrations.loguru.debugbundle_sink, level="ERROR")

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})

# Flush all buffered events
await debugbundle.flush()

Transport

ModeWhen UsedDescription
httpDefaultSends events to the ingestion API via HTTPS.
fileLocal-onlyWrites events to .debugbundle/local/events/ for CLI processing.

The transport is selected automatically based on your connection.json mode, or can be overridden with the transport config option.

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_suppressed event.
  • Loop protection — More than 10 identical errors in 2 seconds forces suppression. Checkpoint every 30 seconds. Resets after 60 seconds of silence.
  • Buffer retention — Events are never dropped on transport failure. Respects Retry-After headers from the ingestion API.

Next Steps

On this page