Skip to main content

logbrew-fastapi

LogBrew logo

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

Install

python3 -m pip install logbrew-fastapi

The package is typed, ships py.typed, and installs the compatible core logbrew-sdk. It supports FastAPI 0.111.1 and later. It does not install or replace application-owned HTTP clients such as httpx or httpx2. Keep the real project key in application configuration rather than source control.

Production setup

import logging
import os

from fastapi import FastAPI
from logbrew_fastapi import init_logbrew

app = FastAPI()
logbrew = init_logbrew(
    app,
    api_key=os.environ["LOGBREW_API_KEY"],
    service_name="checkout-api",
)
client = logbrew.client
logger = logging.getLogger("checkout-api")
logger.addHandler(logbrew.logging_handler)


@app.get("/health")
def health() -> dict[str, bool]:
    logger.info("health request")
    return {"ok": True}

init_logbrew() records successful requests as spans and unhandled handler exceptions as issues plus error spans. It owns a real HttpTransport, uses the core SDK's bounded background delivery, and performs a final exact flush after the app's own default or custom FastAPI lifespan teardown. Network delivery never blocks the request path.

The returned runtime exposes content-free delivery diagnostics:

health = logbrew.delivery_health()
print(
    {
        "state": health.lifecycle,
        "pending": health.pending_events,
        "dropped": health.dropped_events,
        "pauseReason": health.pause_reason,
    }
)

Final delivery failures surface during lifespan shutdown by default, after requests have stopped serving. Set raise_shutdown_errors=False only when the application must preserve shutdown despite a telemetry failure; logbrew.shutdown_error_code and delivery_health() remain available without event content, API keys, endpoint configuration, or exception text.

The logging handler is returned but never attached globally. Add it only to the logger whose records you intend to capture. It automatically correlates logs emitted during a request with that request's traceId, spanId, parentSpanId, and sampled state.

When an incoming request has a valid W3C traceparent header, request capture continues that trace by using the incoming trace ID and parent span ID while creating a fresh child span ID. The same request-local trace is available from get_active_logbrew_trace() while a handler runs. Missing or malformed headers start a fresh W3C-shaped local trace so bad client headers do not break the app.

Request spans use the FastAPI route template, such as GET /orders/{order_id}, for low-noise grouping. 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.

Caller-owned delivery

Use add_logbrew_middleware() when the application already owns its LogBrewClient and transport lifecycle, or when a deterministic local preview needs RecordingTransport. This low-level API accepts any object implementing the public Transport protocol:

from logbrew_fastapi import add_logbrew_middleware
from logbrew_sdk import LogBrewClient, RecordingTransport

client = LogBrewClient.create(
    api_key="LOGBREW_API_KEY",
    sdk_name="checkout-api",
    sdk_version="1.0.0",
)
transport = RecordingTransport.always_accept()
add_logbrew_middleware(
    app,
    client=client,
    transport=transport,
    span_id_factory=lambda: "b7ad6b7169203331",
)

The low-level middleware flushes through the provided transport after each response by default. If no transport is provided, events remain queued for the application to flush. Transport failures do not break the request path unless raise_flush_errors=True.

Outbound HTTP child spans

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

from logbrew_sdk import requests_request_with_logbrew_span


@app.post("/checkout/{order_id}")
def checkout(order_id: str) -> dict[str, object]:
    response = requests_request_with_logbrew_span(
        "POST",
        "https://payments.example.com/payments/authorize",
        client=client,
        event_id="evt_fastapi_outbound_payment",
        request=fake_payment_request,
        route_template="/payments/authorize",
        metadata={"dependency": "payments", "operation": "authorize"},
    )
    return {"ok": response.status_code == 202, "orderId": order_id}

Run python -m logbrew_fastapi.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 FastAPI 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

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

from logbrew_sdk import (
    cache_operation_with_logbrew_span,
    database_operation_with_logbrew_span,
    queue_operation_with_logbrew_span,
)


@app.post("/checkout/{order_id}")
def checkout(order_id: str) -> dict[str, object]:
    inventory = database_operation_with_logbrew_span(
        "SELECT inventory",
        client=client,
        event_id="evt_fastapi_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_fastapi_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_fastapi_dependency_queue",
        operation=publish_checkout_event,
        system="memory-queue",
        operation_kind="publish",
        queue_name="checkout-events",
        task_name="checkout.completed",
        message_count=1,
    )
    return {"ok": inventory is not None and cached_count >= 0, "orderId": order_id}

Run python -m logbrew_fastapi.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:

logbrew = init_logbrew(
    app,
    api_key=os.environ["LOGBREW_API_KEY"],
    service_name="checkout-api",
    capture_request_metrics=True,
)

The metric includes primitive, low-cardinality metadata: service, 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.

Use a clearly fake placeholder like LOGBREW_API_KEY in examples.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

logbrew_fastapi-0.1.6.tar.gz (13.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

logbrew_fastapi-0.1.6-py3-none-any.whl (15.1 kB view details)

Uploaded Python 3

File details

Details for the file logbrew_fastapi-0.1.6.tar.gz.

File metadata

  • Download URL: logbrew_fastapi-0.1.6.tar.gz
  • Upload date:
  • Size: 13.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for logbrew_fastapi-0.1.6.tar.gz
Algorithm Hash digest
SHA256 32e9bc424173007f70507905596e9e09b960945b3477e4b09971c1cb16645459
MD5 f464fda7ead9bbe1a36aa5cd0911ac49
BLAKE2b-256 9ee101df31355f7ce029dbf0dae0b195174b01e5e0895c20eecf79d23f9caaa2

See more details on using hashes here.

Provenance

The following attestation bundles were made for logbrew_fastapi-0.1.6.tar.gz:

Publisher: publish-packages.yml on LogBrewCo/sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file logbrew_fastapi-0.1.6-py3-none-any.whl.

File metadata

  • Download URL: logbrew_fastapi-0.1.6-py3-none-any.whl
  • Upload date:
  • Size: 15.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for logbrew_fastapi-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 936a6906d4c72da5440e0bd4b94adea4d6fc22b11c8c7dd4459bf486081a8146
MD5 715c534510b67a03001e682f3207660c
BLAKE2b-256 1ee371c84d7e66727ae6dc7dbdae9335e1dc6e8075125f88e2e2e737e4c8c172

See more details on using hashes here.

Provenance

The following attestation bundles were made for logbrew_fastapi-0.1.6-py3-none-any.whl:

Publisher: publish-packages.yml on LogBrewCo/sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.1.10

2 files

0.1.9

2 files

0.1.8

2 files

0.1.7

2 files

This release

0.1.6 This release

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

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