Metadata-Version: 2.4
Name: aissue
Version: 2.0.0
Summary: Report errors from Python, Django, Flask and FastAPI apps to AIssue
Home-page: https://aissue.dev
Author: AIssue Team
Author-email: support@aissue.dev
License: MIT
Project-URL: Homepage, https://aissue.dev
Project-URL: Setup guide, https://aissue.dev/setup/
Project-URL: Documentation, https://aissue.dev/install/python.md
Keywords: django flask fastapi starlette asgi error monitoring error tracking breadcrumbs sentry-compatible aissue
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Framework :: Django
Classifier: Framework :: Django :: 4.2
Classifier: Framework :: Django :: 5.0
Classifier: Framework :: Django :: 5.1
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Flask
Classifier: Framework :: FastAPI
Classifier: Topic :: Software Development :: Bug Tracking
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.25.0
Provides-Extra: django
Requires-Dist: Django>=3.2; extra == "django"
Provides-Extra: flask
Requires-Dist: Flask>=2.2; extra == "flask"
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.95; extra == "fastapi"
Provides-Extra: starlette
Requires-Dist: starlette>=0.27; extra == "starlette"
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: pytest-django>=4.0; extra == "dev"
Requires-Dist: Flask>=2.2; extra == "dev"
Requires-Dist: fastapi>=0.95; extra == "dev"
Requires-Dist: httpx>=0.23; extra == "dev"
Requires-Dist: black>=21.0; extra == "dev"
Requires-Dist: flake8>=3.8; extra == "dev"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# aissue: error reporting for Python, Django, Flask and FastAPI

Send your app's errors to [AIssue](https://aissue.dev), which groups them into issues, finds the code responsible and explains how to fix it.

## Django: 3 steps

```bash
pip install aissue
```

```python
# settings.py
MIDDLEWARE = [
    # ... your existing middleware
    "aissue.middleware.AIssueMiddleware",
]
```

```bash
# where the app runs (.env, Docker, your host's settings)
AISSUE_DSN=https://<key>@<your-aissue-host>/<domain id>
```

Copy the exact `AISSUE_DSN` from your domain page in AIssue (**Set up error reporting → Django**). That's it: unhandled view errors are reported when `DEBUG = False`, in a background thread, without slowing down requests.

### Also report errors you catch and log

```python
LOGGING = {
    "version": 1,
    "handlers": {
        "console": {"class": "logging.StreamHandler"},
        "aissue": {"class": "aissue.logging.AIssueHandler", "level": "ERROR"},
    },
    "root": {"handlers": ["console", "aissue"], "level": "INFO"},
}
```

Any `logger.exception(...)` (or `logger.error(..., exc_info=True)`) is then reported. Records without exception information are ignored.

## Flask

```bash
pip install "aissue[flask]"
```

```python
from flask import Flask
from aissue.flask import AIssue

app = Flask(__name__)
AIssue(app)  # reads AISSUE_DSN from app.config or the environment
```

Or with an application factory:

```python
aissue_ext = AIssue()

def create_app():
    app = Flask(__name__)
    aissue_ext.init_app(app)
    return app
```

Unhandled exceptions (Flask's `got_request_exception`) are reported with status 500, the path, method, filtered query parameters, allow-listed headers, release, environment and the request's breadcrumbs. `abort(404)` and other HTTP errors are not reported. Nothing is reported while `app.debug` is on unless you pass `log_in_debug=True`.

Options, as keyword arguments or `AISSUE_*` keys in `app.config`: `dsn`, `environment`, `release`, `enabled`, `log_in_debug`, `header_allowlist`, `timeout`, `max_breadcrumbs`, `breadcrumb_log_level`, `http_breadcrumbs`. To send a user id, pass a callable that gets the request and returns an opaque id (never an email):

```python
AIssue(app, user_id=lambda request: getattr(current_user, "id", None))  # e.g. Flask-Login
```

## FastAPI and Starlette

```bash
pip install "aissue[fastapi]"
```

```python
from fastapi import FastAPI
import aissue.fastapi

app = FastAPI()
aissue.fastapi.init(app)  # reads AISSUE_DSN; or init(app, dsn="https://...", environment="production")
```

`aissue.fastapi.init` adds `aissue.asgi.AIssueMiddleware`, a plain ASGI middleware. Use it directly for Starlette or any other ASGI app:

```python
from aissue.asgi import AIssueMiddleware

app.add_middleware(AIssueMiddleware, dsn="https://...")   # Starlette / FastAPI
app = AIssueMiddleware(app)                               # any ASGI app
```

Unhandled exceptions are reported and then re-raised, so the framework still answers 500. Handled errors (`HTTPException`, your exception handlers) are not reported. Events are handed to the SDK's background thread, so nothing blocks the event loop. Options: the same as Flask, plus `report_4xx`; `user_id` is a callable that gets the ASGI `scope` (by default the id of an authenticated Starlette `scope["user"]` is used).

## Any other Python app (scripts, workers)

```python
import aissue

aissue.init()  # reads AISSUE_DSN; or aissue.init(dsn="https://...")

try:
    charge(order)
except Exception as exc:
    aissue.capture_exception(exc)
    raise
```

Without a DSN (or with an invalid one), `aissue.init()` logs a warning and returns a disabled client that does nothing: it never raises. Call `aissue.flush()` before a short-lived script exits to wait until queued events are sent.

## Breadcrumbs

Each error is sent with a short trail of what happened before it (at most 100 items, oldest first):

- **Requests:** the incoming request (`GET /checkout`, path only).
- **Logs:** Python `logging` records at INFO and above (the level your loggers actually emit). The SDK's own logs and `urllib3`/`requests` internals are skipped.
- **Outbound HTTP:** calls made with `requests`: method, URL without the query string, and status code. Requests to AIssue itself are skipped.
- **Your own:**

```python
import aissue

aissue.add_breadcrumb("Applied coupon", category="checkout", level="info", data={"items": 3})
aissue.clear_breadcrumbs()
```

`type` can be `default`, `http`, `navigation`, `ui`, `log` or `query`; `level` one of `debug`, `info`, `warning`, `error`; `data` a flat dict of strings, numbers and booleans (at most 20 keys); messages are cut at 1000 characters.

Each request (Django, Flask, FastAPI/ASGI) gets its own trail, kept in a `contextvars` variable, so concurrent requests, threads and asyncio tasks never mix. Outside a request, breadcrumbs go to one process-wide trail. To give a background job its own trail:

```python
with aissue.breadcrumb_scope():
    process(job)
```

Breadcrumb messages and data go through the same filters as the rest of the event: values under sensitive keys become `[Filtered]`, and secrets in text (`password=...`, `Bearer ...`, API keys, card numbers, email addresses) are redacted.

| Option (`aissue.init`, Flask, ASGI) | Django setting | Default | |
|---|---|---|---|
| `max_breadcrumbs` | `AISSUE_MAX_BREADCRUMBS` | `50` | Trail length, up to 100. `0` turns breadcrumbs off. |
| `breadcrumb_log_level` | `AISSUE_BREADCRUMB_LOG_LEVEL` | `"INFO"` | Lowest log level recorded. `None` turns log breadcrumbs off. |
| `http_breadcrumbs` | `AISSUE_HTTP_BREADCRUMBS` | `True` | Record outbound `requests` calls. |

If you already use the Sentry SDK, you don't need this package: set its DSN to the AIssue DSN instead (see your domain page).

## Settings

All optional except the DSN. Each can also be an environment variable of the same name where noted.

| Setting | Default | |
|---|---|---|
| `AISSUE_DSN` | env `AISSUE_DSN` | `https://<key>@<host>/<domain id>` |
| `AISSUE_ENVIRONMENT` | env `AISSUE_ENVIRONMENT` | e.g. `production` |
| `AISSUE_RELEASE` | auto-detected | Deployed version. A git commit SHA lets AIssue read the exact deployed code. Detected from `AISSUE_RELEASE`, `VERCEL_GIT_COMMIT_SHA`, `RENDER_GIT_COMMIT`, `RAILWAY_GIT_COMMIT_SHA`, `HEROKU_SLUG_COMMIT`, `SOURCE_VERSION`, `CF_PAGES_COMMIT_SHA`, `GITHUB_SHA`, `COMMIT_SHA`, `GIT_SHA`, `GIT_COMMIT`. In Docker, pass one in, e.g. `--build-arg`/`ENV GIT_SHA=$(git rev-parse HEAD)`. |
| `AISSUE_ENABLED` | `True` (env `AISSUE_ENABLED` for `aissue.init`) | Turn reporting off. The Django middleware then removes itself. |
| `AISSUE_LOG_IN_DEBUG` | `False` | Also report while `DEBUG = True` |
| `AISSUE_REPORT_4XX` | `False` | Also report `Http404`, `PermissionDenied` and 400 errors |
| `AISSUE_SEND_REQUEST_BODY` | `False` | Send form data and JSON bodies (up to 64 KB), sensitive keys still filtered. Other bodies (plain text, XML, raw multipart) are never sent. |
| `AISSUE_SEND_USER_EMAIL` | `False` | Send the signed-in user's email (the user id is always sent) |
| `AISSUE_HEADER_ALLOWLIST` | safe default | Header names to send |
| `AISSUE_TIMEOUT` | `5` | Seconds per request to AIssue |
| `AISSUE_MAX_BREADCRUMBS`, `AISSUE_BREADCRUMB_LOG_LEVEL`, `AISSUE_HTTP_BREADCRUMBS` | | See [Breadcrumbs](#breadcrumbs) |

Legacy: `AISSUE_API_KEY` + `AISSUE_BASE_URL` still work instead of `AISSUE_DSN`.

A missing or invalid DSN never stops your app from starting: the middleware logs an `aissue` warning and removes itself.

## What is sent

- **Error details:** exception type and message, the traceback, and structured stack frames (file, function, line, and whether it is your code or a library).
- **Request:** path, method, and query parameters. Values under sensitive-looking keys (`password`, `token`, `api_key`, `session`, `cookie`, `auth`, `card`…) are replaced with `[Filtered]`.
- **Headers:** an allowlist only (`User-Agent`, `Content-Type`, `Accept`, `Accept-Language`, `Host`, `Origin`, `Referer` without its query string…). Never `Cookie`, `Authorization`, API-key or client-IP headers.
- **User:** the signed-in user's id only.
- **Deployment:** release and environment.
- **Breadcrumbs:** see [Breadcrumbs](#breadcrumbs).

AIssue scrubs every event again on arrival. Sending never raises into your app. Events are dropped, not queued without limit, if AIssue is unreachable. The SDK backs off when AIssue asks it to (HTTP 429).

## Troubleshooting

- **Nothing arrives:** check `DEBUG = False` (or `AISSUE_LOG_IN_DEBUG = True`; Flask: `app.debug` off or `log_in_debug=True`) and that `AISSUE_DSN` is set where the app runs. Look for `aissue` warnings in your logs, e.g. `AIssue is disabled` or a rejected key (401).
- **No log breadcrumbs:** only records your loggers actually emit are recorded. Python's default level is WARNING, so set `logging.basicConfig(level=logging.INFO)` (or your logging config) to see INFO records.
- **404s show up:** they're not reported unless `AISSUE_REPORT_4XX = True`.
- **Turn it off temporarily:** `AISSUE_ENABLED = False`.

## License

MIT (see [LICENSE](LICENSE)).
