# Starlette | Sentry for Python

The Starlette integration adds support for the [Starlette Framework](https://www.starlette.io/.md).

## [Install](https://docs.sentry.io/.md#install)

Install `sentry-sdk` from PyPI with the `starlette` extra:

```bash
pip install "sentry-sdk[starlette]"
```

## [Configure](https://docs.sentry.io/.md#configure)

If you have the `starlette` package in your dependencies, the Starlette integration will be enabled automatically when you initialize the Sentry SDK.

Error Monitoring\[ ]Tracing\[ ]Profiling\[ ]Logs (Beta)

```python
import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    # Add data like request headers and IP for users, if applicable;
    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
    send_default_pii=True,
    #  performance
    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for tracing.
    traces_sample_rate=1.0,
    #  performance
    #  profiling
    # To collect profiles for all profile sessions,
    # set `profile_session_sample_rate` to 1.0.
    profile_session_sample_rate=1.0,
    # Profiles will be automatically collected while
    # there is an active span.
    profile_lifecycle="trace",
    #  profiling
    #  logs

    # Enable logs to be sent to Sentry
    _experiments={
        "enable_logs": True,
    },
    #  logs
)
```

## [Verify](https://docs.sentry.io/.md#verify)

```python
from starlette.applications import Starlette
from starlette.routing import Route

sentry_sdk.init(...)  # same as above

async def trigger_error(request):
    division_by_zero = 1 / 0

app = Starlette(routes=[
    Route("/sentry-debug", trigger_error),
])
```

When you point your browser to [http://localhost:8000/sentry-debug](http://localhost:8000/sentry-debug.md) a transaction will be created in the Performance section of [sentry.io](https://sentry.io/.md). Additionally, an error event will be sent to [sentry.io](https://sentry.io/.md) and will be connected to the transaction.

It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io/.md).

## [Behavior](https://docs.sentry.io/.md#behavior)

* By default, all exceptions leading to an Internal Server Error are reported. The HTTP status codes to report on are configurable via the `failed_request_status_codes` [option](https://docs.sentry.io/.md#options).

* Request data is attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you set `send_default_pii` to `True`.

* If [traces\_sample\_rate](https://docs.sentry.io/platforms/python/configuration/options.md#traces-sample-rate) is set, then performance information is also reported, which you can see on the **Performance** page of [sentry.io](https://sentry.io/.md).

## [Options](https://docs.sentry.io/.md#options)

By adding `StarletteIntegration` explicitly to your `sentry_sdk.init()` call you can set options for `StarletteIntegration` to change its behavior:

```python
from sentry_sdk.integrations.starlette import StarletteIntegration

sentry_sdk.init(
    # ...
    integrations=[
        StarletteIntegration(
            transaction_style="endpoint",
            failed_request_status_codes={403, *range(500, 599)},
            middleware_spans=False,
            http_methods_to_capture=("GET",),
        )
    ],
)
```

You can pass the following keyword arguments to `StarletteIntegration()`:

* `transaction_style`:

  ```python
  async def product_detail(request):
      return JSONResponse({...})

  app = Starlette(routes=[
      Route('/catalog/product/{product_id}', product_detail),
  ])
  ```

  In the above code, the transaction name will be:

  * `"/catalog/product/{product_id}"` if you set `transaction_style="url"`.
  * `"product_detail"` if you set `transaction_style="endpoint"`

  The default is `"url"`.

* `failed_request_status_codes`:

  A `set` of integers that will determine which status codes should be reported to Sentry.

  The `failed_request_status_codes` option determines whether [`HTTPException`](https://www.starlette.io/exceptions.md#httpexception) exceptions should be reported to Sentry. Unhandled exceptions that don't have a `status_code` attribute will always be reported to Sentry.

  Examples of valid `failed_request_status_codes`:

  * `{500}` will only send events on HTTP 500.
  * `{400, *range(500, 600)}` will send events on HTTP 400 as well as the 5xx range.
  * `{500, 503}` will send events on HTTP 500 and 503.
  * `set()` (the empty set) will not send events for any HTTP status code.

  The default is `{*range(500, 600)}`, meaning that all 5xx status codes are reported to Sentry.

* `middleware_spans`:

  Create spans and track performance of all middleware in your Starlette project. Set to `False` to disable.

  The default is `True`.

* `http_methods_to_capture`:

  A tuple containing all the HTTP methods that should create a transaction in Sentry.

  The default is `("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)`.

  (Note that `OPTIONS` and `HEAD` are missing by default.)

  ##### Added in 2.15.0

  The `http_methods_to_capture` option.

## [Supported Versions](https://docs.sentry.io/.md#supported-versions)

* Starlette: 0.19.1+
* Python: 3.7+
