Fictura
Error tracking

Python

pip install fictura, two lines in main.py, and crashes, the errors you already log, the request behind them and your logs arrive with no capture calls to write.

For FastAPI or any ASGI app. Zero dependencies, one stdlib-only module, version 0.6.0. The same file is served at https://api.fictura.co/sdk/fictura.py if you prefer to vendor it.

Install
pip install fictura==0.6.0

Pin it in requirements.txt. Coming from 0.5 or 0.4, nothing in your code changes: see Upgrading.

Wire it

main.py
import fictura
from fastapi import FastAPI

fictura.init(
    service_name="my-api",
    # Optional: the default looks in request.state.user and request.state.user_id.
    get_user_id=lambda scope: scope["state"]["user"]["id"],
)

app = FastAPI()
fictura.instrument(app)

init reads the rest from the environment, and stays off without a key:

VariableWhat it sets
FICTURA_API_KEYThe SDK app key, from Dashboard → Setup.
FICTURA_API_BASEYour Fictura API. Default https://api.fictura.co.
FICTURA_RELEASEWhich deploy an error came from.
FICTURA_ENVIRONMENTKeeps staging out of production's list. Default production.
FICTURA_SERVICE_NAMEThe service's name on spans and logs.

The older form, app.add_middleware(Fictura(api_key=..., api_base=...).middleware), still works, without the tracing, logs, flush on SIGTERM and thread and top-level capture that init adds.

Keep local and test runs out

fictura.init(enabled=False) sends nothing — no errors, logs or traces — whatever key is set. Tie it to an env flag, so a laptop or test box with a production key in .env stays quiet:

main.py
import os

off = os.getenv("FICTURA_OFF", "").strip().lower() in ("1", "true", "yes", "on")
fictura.init(service_name="my-api", enabled=False if off else None)

FICTURA_OFF=true in .env then turns it off, and deleting the line turns it back on. None keeps the default: on when a key is set, off under pytest. If you'd rather keep the events but out of production's list, set FICTURA_ENVIRONMENT=development off your host and add an inbound filter for that environment.

Set get_user_id

Without a user every issue arrives anonymous and "users affected" stays at zero. With one, an error links straight to that user's event history. It is read after your app ran, so a user set by an auth dependency is found.

What gets captured

Crashes, via the middleware. Your own error handling is untouched: it re-raises after queueing. A raise HTTPException(500, ...) is reported too, with the stack of the line that raised it, so it groups on where it was raised, as in Sentry, and an id in its detail text doesn't split it into many issues. If the request already reported the real error (usually a logger.error just before the raise), that event stands and no second one is sent. Uncaught exceptions in threads and at the top level, and unraisable ones, are reported too.

MCP errors. An MCPError raised in an MCP tool, prompt or resource handler is reported as an issue, with its code in the tag mcp.error.code, as Sentry's MCP integration does.

Every logger.error(...) you already write. init attaches a logging handler, so this is already an issue:

Python
try:
    result = await gemini.generate(prompt)
except Exception as e:
    logger.error(f"Generation failed: {e}")   # ← already reported
    return fallback()

You get the full traceback even though nothing passed exc_info=: inside an except block the exception is still live and gets picked up. An exception that is logged and re-raised, or wrapped with raise X from e, is reported once.

A log line with no exception in flight still becomes an issue. It sends log_template, the message before its %-arguments are filled in, and groups on the logger and that template, as Sentry does: logger.error("payment %s failed", order_id) is one issue for every order, and moving the call to another line keeps the issue.

What an event carries

Open an issue and its latest event shows all of this:

What it isOff switch
FramesEach stack frame with its file, function and line, newest first. App frames are marked, using project_root. The frames of what caused the exception (raise X from e) follow its own, and the issue page shows them under each cause.Always on
Source lines5 lines above and below each frame's line.include_source_context=False
Local variablesThe values in app frames and the newest 5 frames, as a short repr: at most 30 a frame and 200 characters a value.capture_locals=False
RequestURL, full query string, method, and headers with sensitive ones filtered.Always on
Request bodyJSON or form bodies, up to max_request_body_size. Your app still reads the body as normal.capture_body=False
Tags and contextsRuntime, server, trace, and the client (app name and version, OS and device from User-Agent; country from cf-ipcountry).Always on
BreadcrumbsUp to 100 per request: log lines at INFO and above, and HTTP calls with method, URL, query, status and reason.breadcrumbs=False
Installed packagesYour dependencies and their versions, folded on the issue page.Always on

max_request_body_size takes "never", "small" (1,000 bytes), "medium" (10,000 bytes, the default) or "always". A body over the limit is left out whole, never cut in half, and the Request panel says so. Cookies, IP addresses and uploaded files are never sent.

What is scrubbed

Before anything leaves the process, values whose key looks sensitive (password, secret, token, api_key, auth, cookie, session, csrf, jwt, credit_card and similar) are replaced, in variables, headers, bodies and query strings. Strings that look like keys or card numbers are masked wherever they appear.

To change the list, pass your own EventScrubber:

Python
fictura.init(event_scrubber=fictura.EventScrubber(denylist=["password", "ssn", "date_of_birth"]))

See Privacy for what this means for your data.

Add your own context

These apply to the current request. Each request has its own scope, threads it starts inherit a copy of it, and nothing leaks into the next request. Outside a request, each thread and task gets its own scope the first time it uses one, as in Sentry, so set_user or a breadcrumb in one cron thread never lands on another thread's errors.

Python
fictura.set_user({"id": user.id})
fictura.set_tag("plan", "pro")
fictura.set_context("checkout", {"step": 3, "items": 2})
fictura.add_breadcrumb(category="payment", message="Card charged", level="info", data={"amount": 1200})

with fictura.new_scope() as scope:        # only for this block
    scope.set_tag("job", "nightly-sync")
    scope.fingerprint = ["nightly-sync"]  # group these together
    run_job()

set_tags, set_extra, get_current_scope(), get_isolation_scope(), get_global_scope(), scope.add_event_processor and add_global_event_processor are there for the rest.

Report something yourself

Python
fictura.capture_exception()                      # the exception being handled
fictura.capture_exception(e, level="warning", tags={"vendor": "stripe"})
fictura.capture_message("Quota nearly used", level="warning", extra={"used": 980})
fictura.capture_event({"message": "Custom", "level": "info"})

All three also take contexts, fingerprint and user.

Tracing

Requests are traced by default (traces_sample_rate) and show on the Performance page. HTTP client calls, AI calls, MCP tools, prompts and resources, and subprocesses become child spans by themselves. HTTP calls over 100 ms also record the line of code that made them. Each request also counts as a session, for a crash-free request rate on the Releases page (request_sessions=False turns that off).

Add spans of your own:

Python
@fictura.trace(op="task", name="Build report")
async def build_report(): ...

with fictura.start_span(op="db", name="Load orders") as span:
    span.set_data("rows", len(orders))
    span.set_status("ok")
    child = span.start_child(op="cache", name="Fill cache")
    child.finish()

fictura.update_current_span(attributes={"tier": "pro"})

start_transaction, get_current_span(), fictura.span() and set_attribute work too. When a request's HTTP calls run one after another and could run together, you get a performance issue.

Background tasks (FastAPI and Starlette BackgroundTasks) are children of the request, in its trace, as in Sentry: each is a span with op task, named after its function. An error in a task that runs after the response keeps the status the client got, not 500. instrument_background_tasks=False turns this off.

Cron jobs

Wrap a scheduled job in fictura.monitor, as a decorator (sync or async) or a context manager:

Python
@fictura.monitor("nightly-sync", schedule="0 3 * * *")
def nightly_sync(): ...

with fictura.monitor("hourly-cleanup"):
    cleanup()

The job runs in its own trace, op cron, named after the slug, with monitor.slug and monitor.schedule. An exception marks it failed and is re-raised. When the job ends, its spans, errors and logs are flushed for up to 5 seconds, because a cron process usually exits right after. Performance → Jobs lists each cron with its last run, its failures and whether it is late: see Cron monitors.

Logs

With init, your log lines at INFO and above also go to the Logs page, joined to their traces. enable_logs=False turns that off. See Logs.

Options

Pass these to init.

OptionDefaultWhat it does
enabledon when a key is set, off under pytestFalse sends nothing: no errors, logs or traces.
capture_logsTrueReport log records as issues. False for crashes only.
log_levellogging.ERRORThe lowest log level that becomes an issue.
enable_logsTrueSend log lines to the Logs page.
logs_levellogging.INFOThe lowest log level sent to the Logs page.
before_send_lognoneEdit a log line, or return None to drop it.
sample_rate1.0The share of error events kept.
error_samplernoneA function that picks the rate per event.
ignore_errors[]Exception types or names never to report.
before_sendnoneEdit an event, or return None to drop it.
before_breadcrumbnoneEdit a breadcrumb, or return None to drop it.
max_breadcrumbs100How many breadcrumbs an event keeps.
attach_stacktraceFalseAdd a stack to messages captured with no exception.
max_stack_frames100How many frames an event keeps.
add_full_stackFalseInclude the frames above where the exception was caught.
in_app_include, in_app_exclude[]Module prefixes to treat as yours, or not.
project_rootthe current directoryFiles under it count as your own code.
custom_reprnoneHow to print a variable; return None for the default.
max_value_lengthnoneCut long strings in an event to this length.
distnoneA build within a release.
server_namethe host nameThe server shown on events and logs.
shutdown_timeout2Seconds to spend sending what is queued at exit.
traces_sample_rate1.0The share of requests traced.
traces_samplernoneA function that picks the rate per trace.
before_send_transactionnoneEdit a finished trace, or return None to drop it.
functions_to_trace[]Functions to trace by name, such as "app.billing.charge".
trace_ignore_status_codesnoneDon't keep traces of requests ending with these statuses.

Guarantees

Never raises into your app, never blocks a response. Reporting happens on one daemon thread with bounded queues (200 errors, 2,000 spans, 5,000 log lines), oldest dropped first, in batches of up to 20 events under 900 KB. Events flush at exit and on SIGTERM; on Railway, set RAILWAY_DEPLOYMENT_DRAINING_SECONDS to 5 or more so there is time.

When Fictura is slow or restarting, nothing that fits in the queue is lost:

  • A timeout (10 seconds), a network error, a 408 or another 5xx keeps the batch and pauses that queue for 1 s, then 2 s, 4 s and so on up to 60 s, then sends the same batch again with the same event ids.
  • A 429 or 503 keeps the batch and waits for its Retry-After.
  • Any other 4xx drops the batch.

Nothing is dropped silently. A full queue, a 4xx, or a batch that can't be built is counted by queue and reason, and the counts ride on the next batch as dropped, for example {"errors": {"queue_full": 3}}. Fictura shows them in tracing health.

Smoke test: with FICTURA_API_KEY and FICTURA_API_BASE set, python -m fictura sends a test event down each capture path and a test log line. They appear on the Issues and Logs pages within seconds.

Upgrading

Nothing to change in your code. New in 0.6.0:

  • Delivery keeps a batch through timeouts, network errors and 5xx, backing off up to 60 s, instead of one retry and a drop. The request timeout is 10 s (it was 2 s). Drops are counted and sent as dropped.
  • A logged error with no exception sends log_template and groups on the logger and the template, so moving the log call keeps the issue.
  • A handled HTTPException(500) sends the stack of where it was raised and groups on it, not on its detail text.
  • MCPError from an MCP handler is reported, with the tag mcp.error.code.
  • Background tasks are back in the request's trace, as its children. An error in a task after the response keeps the response's status.
  • Outside a request, each thread and task gets its own scope.

New in 0.5: Supabase REST calls are db spans with the table and operation; HTTP client spans have http.response.body.size; spans sampled by a rate carry fictura.sample_rate; fictura.monitor() for cron jobs; Gemini spans have gen_ai.provider.name.

On this page