You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In addition to capturing errors, you can monitor interactions between multiple services or applications by [enabling tracing](/concepts/key-terms/tracing/).
17
+
18
+
Send <PlatformLinkto="/platforms/python/logs/">structured logs</PlatformLink> to Sentry and correlate them with errors and traces.
19
+
20
+
FastAPI-specific behavior and performance coverage:
21
+
22
+
- By default, all exceptions leading to an Internal Server Error are captured and reported. You can configure which status codes are reported via the `failed_request_status_codes` option.
23
+
- Request data (URL, HTTP method, headers, form data, JSON payloads) is attached to issues. Raw bodies and multipart file uploads are excluded.
24
+
- PII (like user IDs, usernames, cookies, auth headers, IPs) is excluded unless you set `send_default_pii=True`.
Install `sentry-sdk` from PyPI with the `fastapi` extra:
43
+
Install the Sentry SDK using the FastAPI extra:
11
44
12
45
```bash {tabTitle:pip}
13
46
pip install "sentry-sdk[fastapi]"
@@ -18,69 +51,219 @@ uv add "sentry-sdk[fastapi]"
18
51
19
52
## Configure
20
53
21
-
If you have the `fastapi` package in your dependencies, the FastAPI integration will be enabled automatically when you initialize the Sentry SDK.
54
+
Configuration should happen as early as possible in your application's lifecycle. If `fastapi` is in your dependencies, the FastAPI integration is enabled automatically when you initialize the SDK.
55
+
56
+
```python {filename:main.py}
57
+
import sentry_sdk
58
+
59
+
sentry_sdk.init(
60
+
dsn="___PUBLIC_DSN___",
61
+
62
+
# Adds request headers and IP for users, for more info visit:
The Sentry SDK automatically captures unhandled exceptions. You can also manually capture errors and add context:
24
91
25
-
##Verify
92
+
### Automatic Error Capture
26
93
27
94
```python
28
-
from fastapi import FastAPI
95
+
# This will be automatically captured by Sentry
96
+
division_by_zero =1/0
97
+
```
29
98
30
-
sentry_sdk.init(...) # same as above
99
+
### Manual Error Capture
31
100
32
-
app = FastAPI()
101
+
```python
102
+
import sentry_sdk
33
103
34
-
@app.get("/sentry-debug")
35
-
asyncdeftrigger_error():
36
-
division_by_zero =1/0
104
+
try:
105
+
risky_operation()
106
+
exceptExceptionas e:
107
+
# Capture the exception with additional context
108
+
sentry_sdk.capture_exception(e)
37
109
```
38
110
39
-
When you point your browser to [http://localhost:8000/sentry-debug](http://localhost:8000/sentry-debug) a transaction will be created in the Performance section of [sentry.io](https://sentry.io). Additionally, an error event will be sent to [sentry.io](https://sentry.io) and will be connected to the transaction.
111
+
<Alert>
40
112
41
-
It takes a couple of moments for the data to appear in [sentry.io](https://sentry.io).
113
+
Learn more about manually capturing errors in our <PlatformLinkto="/usage/">Usage documentation</PlatformLink>.
42
114
43
-
## Behaviour
115
+
</Alert>
44
116
45
-
### Issue Reporting
117
+
### Adding User Context
46
118
47
-
The following information about your FastAPI project will be available to you on Sentry.io:
- By default, all exceptions leading to an Internal Server Error are captured and reported. The HTTP status codes to report on are configurable via the `failed_request_status_codes`[option](#options).
50
-
- Request data such as URL, HTTP method, headers, form data, and JSON payloads is attached to all issues.
51
-
- Sentry excludes raw bodies and multipart file uploads.
52
-
- Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you set `send_default_pii` to `True`.
140
+
<OnboardingOptionoptionId="performance">
53
141
54
-

142
+
<OnboardingOptionoptionId="logs">
55
143
56
-
### Monitor Performance
144
+
##Step 4: Sending Logs
57
145
58
-
The following parts of your FastAPI project are monitored:
146
+
Now let's add structured logging to capture application insights. Logs are enabled in your configuration above.
59
147
60
-
- Middleware stack
61
-
- Middleware `send` and `receive` callbacks
62
-
- Database queries
63
-
- Redis commands
148
+
Use Python's logging module to capture structured logs with meaningful attributes that help you debug issues and understand user behavior.
64
149
65
-

150
+
```python
151
+
import logging
152
+
153
+
# Configure Python logging
154
+
logger = logging.getLogger(__name__)
155
+
156
+
# Send structured logs with attributes
157
+
logger.info(
158
+
"User completed checkout",
159
+
extra={
160
+
"user_id": 123,
161
+
"order_id": "order_456",
162
+
"amount": 99.99
163
+
}
164
+
)
66
165
67
-
<Alert>
166
+
logger.error(
167
+
"Payment processing failed",
168
+
extra={
169
+
"error_code": "CARD_DECLINED",
170
+
"user_id": 123,
171
+
"attempt_count": 3
172
+
}
173
+
)
174
+
175
+
# Log with exception information
176
+
try:
177
+
process_payment()
178
+
except PaymentError as e:
179
+
logger.exception(
180
+
"Payment failed with exception",
181
+
extra={"transaction_id": "txn_789"}
182
+
)
183
+
```
68
184
69
-
The parameter [traces_sample_rate](/platforms/python/configuration/options/#traces-sample-rate) needs to be set when initializing the Sentry SDK for performance measurements to be recorded.
185
+
</OnboardingOption>
70
186
71
-
</Alert>
187
+
## Step 5: Custom Traces with Attributes
188
+
189
+
Create custom spans to measure specific operations and add meaningful attributes. This helps you understand performance bottlenecks and debug issues with detailed context.
190
+
191
+
```python
192
+
import sentry_sdk
193
+
194
+
# Create custom spans to measure specific operations
195
+
defprocess_user_data(user_id):
196
+
with sentry_sdk.start_span(
197
+
op="function",
198
+
description="Process User Data",
199
+
data={
200
+
"user_id": user_id,
201
+
"operation": "data_processing",
202
+
"version": "2.1"
203
+
}
204
+
) as span:
205
+
# Your business logic here
206
+
user_data = fetch_user_data(user_id)
207
+
208
+
# Nested span for specific operations
209
+
with sentry_sdk.start_span(
210
+
op="transform",
211
+
description="Transform Data",
212
+
data={
213
+
"record_count": len(user_data),
214
+
"transform_type": "normalize"
215
+
}
216
+
) as inner_span:
217
+
result = transform_user_data(user_data)
218
+
219
+
return result
220
+
221
+
# Add attributes to existing spans
222
+
span = sentry_sdk.get_current_span()
223
+
if span:
224
+
span.set_data("cache_hit", True)
225
+
span.set_data("region", "us-west-2")
226
+
span.set_data("performance_score", 0.95)
227
+
```
228
+
229
+
</OnboardingOption>
230
+
231
+
## Verify Your Setup
232
+
233
+
Let's test your setup and confirm that Sentry is working correctly and sending data to your Sentry project.
234
+
235
+
### Test Error Capturing
236
+
237
+
```python
238
+
from fastapi import FastAPI
239
+
240
+
app = FastAPI()
241
+
242
+
@app.get("/sentry-debug")
243
+
asyncdeftrigger_error():
244
+
division_by_zero =1/0
245
+
```
246
+
247
+
Run your application and visit http://localhost:8000/sentry-debug to send an error and transaction to Sentry.
By adding `FastApiIntegration` to your `sentry_sdk.init()` call explicitly, you can set options for `FastApiIntegration` to change its behavior.
76
-
Because FastAPI is based on the Starlette framework, both integrations, `StarletteIntegration` and `FastApiIntegration`, must be instantiated.
259
+
If you want to customize behavior, you can explicitly add FastAPI/Starlette integrations and set options:
77
260
78
261
```python
79
262
from sentry_sdk.integrations.starlette import StarletteIntegration
80
263
from sentry_sdk.integrations.fastapi import FastApiIntegration
81
264
82
265
sentry_sdk.init(
83
-
#same as above
266
+
#... keep your existing options here ...
84
267
integrations=[
85
268
StarletteIntegration(
86
269
transaction_style="endpoint",
@@ -98,68 +281,20 @@ sentry_sdk.init(
98
281
99
282
You can pass the following keyword arguments to `StarletteIntegration()` and `FastApiIntegration()`:
100
283
101
-
-`transaction_style`:
102
-
103
-
This option lets you influence how the transactions are named in Sentry. For example:
104
-
105
-
```python
106
-
import sentry_sdk
107
-
from sentry_sdk.integrations.starlette import StarletteIntegration
108
-
from sentry_sdk.integrations.fastapi import FastApiIntegration
109
-
110
-
sentry_sdk.init(
111
-
# ...
112
-
integrations=[
113
-
StarletteIntegration(
114
-
transaction_style="endpoint",
115
-
),
116
-
FastApiIntegration(
117
-
transaction_style="endpoint",
118
-
),
119
-
],
120
-
)
121
-
122
-
app = FastAPI()
123
-
124
-
@app.get("/catalog/product/{product_id}")
125
-
asyncdefproduct_detail(product_id):
126
-
return {...}
127
-
```
128
-
129
-
In the above code, the transaction name will be:
130
-
131
-
-`"/catalog/product/{product_id}"` if you set `transaction_style="url"`
132
-
-`"product_detail"` if you set `transaction_style="endpoint"`
284
+
-`transaction_style`: Controls how transactions are named in Sentry. For example, with a route like `@app.get("/catalog/product/{product_id}")`, the transaction will be `"/catalog/product/{product_id}"` when set to `"url"` and `"product_detail"` when set to `"endpoint"`. Default is `"url"`.
285
+
-`failed_request_status_codes`: A set of status codes that should be reported to Sentry for handled HTTP exceptions. Unhandled exceptions without `status_code` are always reported. Defaults to all 5xx.
286
+
-`http_methods_to_capture`: Which HTTP methods create transactions. Default is `("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)`.
133
287
134
-
The default is `"url"`.
135
-
136
-
-`failed_request_status_codes`:
137
-
138
-
A `set` of integers that will determine which status codes should be reported to Sentry.
139
-
140
-
The `failed_request_status_codes` option determines whether [`HTTPException`](https://fastapi.tiangolo.com/reference/exceptions/?h=httpexception) exceptions should be
141
-
reported to Sentry. Unhandled exceptions that don't have a `status_code` attribute will always be reported to Sentry.
142
-
143
-
Examples of valid `failed_request_status_codes`:
144
-
145
-
-`{500}` will only send events on HTTP 500.
146
-
-`{400, *range(500, 600)}` will send events on HTTP 400 as well as the 5xx range.
147
-
-`{500, 503}` will send events on HTTP 500 and 503.
148
-
-`set()` (the empty set) will not send events for any HTTP status code.
149
-
150
-
The default is `{*range(500, 600)}`, meaning that all 5xx status codes are reported to Sentry.
151
-
152
-
-`http_methods_to_capture`:
153
-
154
-
A tuple containing all the HTTP methods that should create a transaction in Sentry.
155
-
156
-
The default is `("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)`.
288
+
<Alerttitle="Added in 2.15.0">
289
+
The `http_methods_to_capture` option.
290
+
</Alert>
157
291
158
-
(Note that `OPTIONS` and `HEAD` are missing by default.)
292
+
## Next Steps
159
293
160
-
<Alerttitle="Added in 2.15.0">
161
-
The `http_methods_to_capture` option.
162
-
</Alert>
294
+
- Continue to <PlatformLinkto="/configuration">customize your configuration</PlatformLink>
295
+
- Learn more about <PlatformLinkto="/platforms/python/integrations/">instrumenting frameworks</PlatformLink>
296
+
- Learn how to <PlatformLinkto="/usage">manually capture errors</PlatformLink>
297
+
- Set up <PlatformLinkto="/configuration/releases/">release tracking</PlatformLink>
0 commit comments