Skip to main content

logbrew-flask

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

python3 -m pip install logbrew-sdk logbrew-flask

logbrew-flask requires Python 3.10 or newer.

The package is typed, ships py.typed, depends on the core logbrew-sdk, and keeps Flask as a normal framework dependency instead of monkeypatching Flask globally.

Use a project-scoped server ingest key in LOGBREW_SERVER_API_KEY. The framework initializer also reads LOGBREW_SERVICE_NAME, LOGBREW_ENVIRONMENT, and LOGBREW_RELEASE when they are present.

from flask import Flask
from logbrew_flask import init_logbrew

app = Flask(__name__)
logbrew = init_logbrew(app)
client = logbrew.client


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

Confirm The Hosted Trace

A local 200 response or a RecordingTransport receipt confirms that the Flask integration created telemetry. It does not confirm that LogBrew accepted, stored, and indexed the event. Use the public CLI for end-to-end confirmation.

First confirm that the CLI has account access. If it reports that it is not authenticated, a human must complete logbrew login before the account read:

logbrew status --json
logbrew projects --json

Use a project-scoped server ingest key in the Flask process; never use the CLI account session for ingestion. The CLI can create an owner-only key file without printing the one-time key:

install -d -m 700 "$HOME/.logbrew"
logbrew projects keys create '<project_id>' \
  --kind server \
  --label "Flask server" \
  --ingest-key-file "$HOME/.logbrew/flask-app.ingest" \
  --json

export LOGBREW_SERVER_API_KEY="$(tr -d '\r\n' < "$HOME/.logbrew/flask-app.ingest")"
export LOGBREW_SERVICE_NAME="flask-app"
export LOGBREW_ENVIRONMENT="production"
export LOGBREW_RELEASE="flask-app@1.0.0"

Run one real request, then read the same project and deployment scope. Explain one returned trace to confirm that the hosted investigation can use the captured evidence:

logbrew read traces \
  --project '<project_id>' \
  --service flask-app \
  --environment production \
  --release flask-app@1.0.0 \
  --since 1h \
  --json

logbrew explain trace '<trace_id>' --json

The complete first-event flow, including new-project creation, correlated logs, exceptions, metrics, shutdown hooks, and recovery, is in the Flask setup guide.

The initializer owns an HTTP transport and sends on a background worker, so a telemetry request does not block the Flask response. The first accepted event wakes delivery immediately. When the Python process exits normally, the client sends any events still queued, for at most 2 seconds. Call logbrew.client.shutdown() from your graceful worker-shutdown hook when you have one. Repeated init_logbrew(app) calls return the same app extension and do not install duplicate hooks.

Use add_logbrew_middleware() when the application already owns a LogBrewClient. Pass a transport for response-path flushing, or give the client an owned transport and set flush_on_response=False for automatic background delivery.

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.

What It Captures

The middleware records one request span for each captured response. It can also record request duration metrics and exception issues.

Request spans use the Flask route template, such as GET /orders/<int:order_id>, for low-noise grouping. Span metadata includes routeTemplate. Concrete request paths are not emitted, and unmatched routes use the fixed <unmatched> label. Valid inbound W3C traceparent headers are continued with a fresh child span id.

Handlers can call get_active_logbrew_trace() or use LogBrewLoggingHandler; logs emitted during the request share the active request trace and span.

from logbrew_flask import get_active_logbrew_trace


@app.get("/orders/<int:order_id>")
def order_detail(order_id: int) -> dict[str, str | None]:
    trace = get_active_logbrew_trace()
    return {"traceId": trace.trace_id if trace else None}

Set capture_request_metrics=True to emit an explicit http.server.duration histogram for each request. Each generated metric carries the stable description Duration of one completed server request. so its purpose remains clear in investigations. Apps can pass span_id_factory when deterministic child span ids are useful for controlled diagnostics; production apps usually let LogBrew generate span ids.

Outbound HTTP Child Spans

When a handler calls another service, use the core Python HTTP helpers inside the Flask request. They automatically reuse the active Flask request trace, create a child span, and inject one W3C traceparent header whose span id matches the emitted outbound span.

from logbrew_sdk import requests_request_with_logbrew_span


@app.post("/checkout/<order_id>")
def checkout(order_id: str) -> dict[str, bool]:
    response = requests_request_with_logbrew_span(
        "POST",
        "https://payments.example.com/payments/authorize",
        client=client,
        event_id="evt_checkout_payment",
        route_template="/payments/authorize",
    )
    return {"accepted": response.status_code == 202}

The helper does not patch requests globally. It records method, low-cardinality route template, status code, trace id, span id, and parent span id. It does not capture full URLs, query strings, request bodies, response bodies, arbitrary headers, cookies, baggage, or tracestate.

Database, Cache, And Queue Child Spans

Use the core dependency helpers inside a Flask handler to connect database, cache, and queue work to the active request trace.

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, bool]:
    inventory = database_operation_with_logbrew_span(
        "SELECT inventory",
        client=client,
        operation=lambda: database.execute("SELECT quantity FROM inventory WHERE sku = ?", ("sku_123",)).fetchone(),
        system="sqlite",
        statement_template="SELECT inventory WHERE sku = ?",
    )
    cached_inventory = cache_operation_with_logbrew_span(
        "GET inventory",
        client=client,
        operation=lambda: cache["sku_123"],
        system="memory-cache",
        cache_name="inventory-cache",
        cache_hit=True,
    )
    published = queue_operation_with_logbrew_span(
        "PUBLISH checkout.completed",
        client=client,
        operation=lambda: queue.append("checkout.completed") or len(queue),
        system="memory-queue",
        operation_kind="publish",
        queue_name="checkout-events",
        task_name="checkout.completed",
    )
    return {"ok": inventory is not None and cached_inventory > 0 and published == 1}

Run python -m logbrew_flask.examples dependency-spans to see a request span with database, cache, and queue child spans under the same trace. These helpers record operation names, systems, status, trace ids, span ids, parent span ids, and primitive metadata. They do not capture SQL bind values, result payloads, queue message payloads, cache values, arbitrary headers, baggage, or tracestate.

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.

Privacy Defaults

LogBrew does not capture concrete request paths, request bodies, response bodies, cookies, arbitrary headers, query strings, raw traceparent values, baggage, or tracestate. Exception issues include first-class exception type, flask.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.

Delivery Failures

By default, transport failures do not break the Flask response path. Set raise_flush_errors=True only when your app wants delivery failures to surface as request errors in controlled diagnostics.

Tradeoff

Other tools, including OpenTelemetry instrumentation, provide broader automatic Flask, outbound HTTP, and dependency instrumentation, including global patching and deeper view/template/client hooks. LogBrew starts with explicit app-owned Flask and dependency helpers because that keeps setup reversible, simple to reason about, and safer for privacy-sensitive services.

Metadata

Release files for logbrew-flask 0.1.9

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-flask 0.1.9
File Size Uploaded Provenance Actions
logbrew_flask-0.1.9.tar.gz 25.0 kB With provenance Details for logbrew_flask-0.1.9.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for logbrew-flask 0.1.9
File Interpreter ABI Platform Actions
logbrew_flask-0.1.9-py3-none-any.whl Python 3 none any Details for logbrew_flask-0.1.9-py3-none-any.whl

Total release size: 44.1 kB

Release files / logbrew_flask-0.1.9.tar.gz

Download URL logbrew_flask-0.1.9.tar.gz
Size 25.0 kB
Tags Source
SHA-256 checksum
How to use checksums
5aa9d8217af1a17010f0127f8412f2ace6aa7047aa3d82a8c7764b55d9ff709c
BLAKE2b-256 checksum
How to use checksums
fe2dfc678075be6e74fefef03491dc54db7408d0bbfc7170385253f2ed997323
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 29, 2026.

Transparency log

Release files / logbrew_flask-0.1.9-py3-none-any.whl

Download URL logbrew_flask-0.1.9-py3-none-any.whl
Size 19.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d32b5391a4a327253b702ace87ce0be1b3d70c90cc02958efc535a0e68c3cea3
BLAKE2b-256 checksum
How to use checksums
1dd59abfaf1d7eb0ab942b5943dd2fc1b6754b72bc2c314bc708e3e67b575051
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 29, 2026.

Transparency log

Security for logbrew-flask 0.1.9

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_flask-0.1.9.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 29, 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