Skip to main content

logbrew-django

LogBrew logo

Django integration for capturing LogBrew request spans and exceptions with the public Python SDK.

Install

python3 -m pip install logbrew-sdk logbrew-django

logbrew-django requires Python 3.10 or newer and supports Django>=4.2.30,<7, including Django 6.0 and 6.1.

The package is typed, ships py.typed, depends on the core logbrew-sdk, and keeps Django as a normal framework dependency instead of owning the user's project layout.

Example

# settings.py
MIDDLEWARE = [
    "logbrew_django.LogBrewDjangoMiddleware",
    *MIDDLEWARE,
]
# app startup code, for example at the end of settings.py
import logging
import os

from logbrew_django import configure_logbrew, get_active_logbrew_trace
from logbrew_sdk import HttpTransport, LogBrewClient, LogBrewLoggingHandler

client = LogBrewClient.create(
    api_key=os.environ["LOGBREW_SERVER_API_KEY"],
    sdk_name="logbrew-django",
    sdk_version="0.1.10",
)
logger = logging.getLogger("checkout-api")
logger.addHandler(LogBrewLoggingHandler(client, metadata={"service": "checkout-api"}))
configure_logbrew(client=client, transport=HttpTransport(), service_name="checkout-api")

Use a project server ingest key from the environment, never from source. Set LOGBREW_ENVIRONMENT and LOGBREW_RELEASE (for example checkout-api@1.4.0) in the app's environment; the client adds them to every event, so issues show which deploy they belong to. Keep sdk_name and sdk_version as the SDK's own name and version. To keep events in memory instead of sending them, pass RecordingTransport.always_accept() instead of HttpTransport(), and a fixed span_id_factory for stable span ids.

LogBrewDjangoMiddleware records successful requests as span events, records unhandled view exceptions as issue plus error-span events, and flushes through the configured transport after each response. Exceptions that Django turns into 4xx responses (Http404, PermissionDenied, BadRequest, SuspiciousOperation, and MultiPartParserError) are client errors: their request span keeps the 4xx status and no issue is created. Exception issues include first-class exception type, django.middleware mechanism, unhandled state, and up to 32 sanitized newest-first traceback frames. The frame projection contains basename and bounded code identity only; it omits raw traceback text, source code, local variables, and absolute paths. Automatic capture never reads or sends exception messages: the issue uses the fixed summary Unhandled exception, and every exception-chain node is marked redacted. If no transport is provided, events stay queued on the core client so the project can flush them itself.

When an incoming request has a valid W3C traceparent header, request capture continues that trace by using the incoming traceId and parent span id while creating a fresh child span id. The same request-local trace is available from get_active_logbrew_trace() while your view runs, and LogBrewLoggingHandler automatically adds traceId, spanId, parentSpanId, and sampled metadata to standard-library logs emitted inside that context:

def checkout_view(request):
    trace = get_active_logbrew_trace()
    logger.info("checkout request", extra={"traceId": trace.trace_id if trace else None})
    ...

Missing or malformed traceparent headers start a fresh W3C-shaped local trace so bad client headers do not break the project.

Request spans use the Django resolver route template, such as GET /orders/<int:order_id>/, for low-noise grouping. Regex routes from re_path() become readable templates: a named group becomes <name> and any other pattern becomes <var>, so Wagtail's page route ^((?:[\w\-]+/)*)$ is named GET /<var>. Span metadata includes routeTemplate; concrete dynamic paths are not emitted when a route template is available. The trace helper never exposes the raw header, request headers, body, cookies, query strings, or response body.

Read Events Back

A successful send shows that LogBrew accepted the request. It does not show that you can read the event. After your app sends one event, read it back with a project read key:

logbrew projects keys create "<project_id>" --kind read \
  --ingest-key-file "$HOME/.logbrew/setup-check.read" --json
export LOGBREW_TOKEN="$(< "$HOME/.logbrew/setup-check.read")"
logbrew read logs --since 1h --json
logbrew issues --since 1h --json

A read key reads 1 project and cannot send telemetry. Run unset LOGBREW_TOKEN when you finish. Read your events back covers key kinds, empty results, and how to revoke the key.

Request User

Call set_logbrew_user() once you know who made the request, for example after authentication. Every later event of that request, including the request span and any issue, carries context.subject:

from logbrew_sdk import set_logbrew_user

set_logbrew_user(account.public_id)  # an opaque app-owned ID, not an email address or name

The ID stays with its own request trace, so it never reaches another request's events. Outside a request the call does nothing and returns False. Pass kind="anonymous" for visitors who have not signed in. IDs are 1 to 200 characters without control characters. LogBrew stores only the ID and kind; it never collects email addresses, names, or IP addresses for you.

Outbound HTTP child spans

Django views can wrap a caller-owned HTTP request seam with requests_request_with_logbrew_span(...) to create an outbound child span under the active Django request trace and inject a normalized W3C traceparent header:

from django.http import JsonResponse
from logbrew_sdk import requests_request_with_logbrew_span


def checkout_view(request, order_id):
    response = requests_request_with_logbrew_span(
        "POST",
        "https://payments.example.com/payments/authorize",
        client=client,
        event_id="evt_django_outbound_payment",
        request=fake_payment_request,
        route_template="/payments/authorize",
        metadata={"dependency": "payments", "operation": "authorize"},
    )
    return JsonResponse({"ok": response.status_code == 202, "orderId": order_id})

Run python -m logbrew_django.examples outbound-http to see the same local flow from an installed package. The example shows the outgoing traceparent span id matching the emitted outbound span id, and the outbound span's parent is the active Django request span. LogBrew does not globally patch requests, create sessions, capture request or response bodies, serialize headers, store full URLs, or keep query strings.

Database, cache, and queue child spans

Django views can also wrap app-owned dependency work with the core Python helpers. The active Django request trace becomes the parent for each dependency span:

from django.http import JsonResponse
from logbrew_sdk import (
    cache_operation_with_logbrew_span,
    database_operation_with_logbrew_span,
    queue_operation_with_logbrew_span,
)


def checkout_view(request, order_id):
    inventory = database_operation_with_logbrew_span(
        "SELECT inventory",
        client=client,
        event_id="evt_django_dependency_database",
        operation=select_inventory,
        system="sqlite",
        db_name="checkout",
        statement_template="SELECT inventory WHERE sku = ?",
        row_count=1,
    )
    cached_count = cache_operation_with_logbrew_span(
        "GET inventory",
        client=client,
        event_id="evt_django_dependency_cache",
        operation=read_inventory_cache,
        system="memory-cache",
        cache_name="inventory-cache",
        cache_hit=True,
    )
    queue_operation_with_logbrew_span(
        "PUBLISH checkout.completed",
        client=client,
        event_id="evt_django_dependency_queue",
        operation=publish_checkout_event,
        system="memory-queue",
        operation_kind="publish",
        queue_name="checkout-events",
        task_name="checkout.completed",
        message_count=1,
    )
    return JsonResponse({"ok": inventory is not None and cached_count >= 0, "orderId": order_id})

Run python -m logbrew_django.examples dependency-spans to see a local request span parenting SQLite, cache, and queue child spans from an installed package. LogBrew does not patch database drivers, cache clients, queue frameworks, or broker metadata globally, and the helpers avoid SQL values, cache keys/values, queue bodies, headers, baggage, and tracestate.

Request duration metrics are opt-in. Set capture_request_metrics=True to emit an explicit http.server.duration histogram for completed requests. Each generated metric carries the stable description Duration of one completed server request. so its purpose remains clear in investigations:

configure_logbrew(
    client=client,
    transport=transport,
    capture_request_metrics=True,
)

The metric includes primitive, low-cardinality metadata: framework, method, routeTemplate, statusCode, and statusCodeClass. Query strings and URL hashes are omitted. Set capture_successful_requests=False with capture_request_metrics=True when you only want duration metrics and not successful request spans. Avoid user IDs, request payloads, headers, or free-form text in custom metric metadata.

By default, transport failures do not break the Django response path. Set raise_flush_errors=True only when your project wants delivery failures to surface as request errors.

Use a clearly fake placeholder like LOGBREW_API_KEY in examples.

Metadata

Release files for logbrew-django 0.1.10

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for logbrew-django 0.1.10
File Size Uploaded Provenance Actions
logbrew_django-0.1.10.tar.gz 22.0 kB With provenance Details for logbrew_django-0.1.10.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for logbrew-django 0.1.10
File Interpreter ABI Platform Actions
logbrew_django-0.1.10-py3-none-any.whl Python 3 none any Details for logbrew_django-0.1.10-py3-none-any.whl

Total release size: 40.5 kB

Release files / logbrew_django-0.1.10.tar.gz

Download URL logbrew_django-0.1.10.tar.gz
Size 22.0 kB
Tags Source
SHA-256 checksum
How to use checksums
141a38157bd6892baf4b78313914ffb006a134325e676e37cdcbcfa6725a92e2
BLAKE2b-256 checksum
How to use checksums
2475ddcdcae5d7fc4955dbb82a7e37fc3a08962fd80283532d151ec5ef08c5a7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

Release files / logbrew_django-0.1.10-py3-none-any.whl

Download URL logbrew_django-0.1.10-py3-none-any.whl
Size 18.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d72b59cf39f364fe1faddd3bb2b3f1e6c67f932a57a59cb90cfc20a32e2286d9
BLAKE2b-256 checksum
How to use checksums
b08a50f93e692fceaf054115e325115cf1c996fef8b3d5b590be1b6ee42be42a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

Security for logbrew-django 0.1.10

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for logbrew_django-0.1.10.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page