0
# Integrations
1
2
Framework and library integrations for automatic instrumentation including web frameworks, databases, HTTP clients, task queues, AI/ML libraries, and 40+ other popular Python packages.
3
4
## Capabilities
5
6
### Integration System
7
8
The base integration system provides automatic setup and configuration for popular Python libraries and frameworks.
9
10
```python { .api }
11
class Integration(ABC):
12
"""Base class for all Sentry integrations."""
13
14
identifier: str # Unique integration identifier
15
16
@staticmethod
17
@abstractmethod
18
def setup_once() -> None:
19
"""
20
Initialize the integration. Called once when integration is enabled.
21
This method performs monkey-patching, hooks installation, and other
22
setup required for automatic instrumentation.
23
"""
24
```
25
26
### Web Framework Integrations
27
28
Automatic instrumentation for popular Python web frameworks with request tracking, error capture, and performance monitoring.
29
30
#### Django Integration
31
32
```python { .api }
33
class DjangoIntegration(Integration):
34
def __init__(
35
self,
36
transaction_style: str = "url",
37
middleware_spans: bool = True,
38
signals_spans: bool = True,
39
cache_spans: bool = True
40
): ...
41
```
42
43
**Usage:**
44
45
```python
46
import sentry_sdk
47
from sentry_sdk.integrations.django import DjangoIntegration
48
49
sentry_sdk.init(
50
dsn="your-dsn-here",
51
integrations=[
52
DjangoIntegration(
53
transaction_style="url", # 'url' or 'function_name'
54
middleware_spans=True, # Create spans for middleware
55
signals_spans=True, # Create spans for Django signals
56
cache_spans=True # Create spans for cache operations
57
),
58
]
59
)
60
```
61
62
#### Flask Integration
63
64
```python { .api }
65
class FlaskIntegration(Integration):
66
def __init__(self, transaction_style: str = "endpoint"): ...
67
```
68
69
**Usage:**
70
71
```python
72
import sentry_sdk
73
from sentry_sdk.integrations.flask import FlaskIntegration
74
75
sentry_sdk.init(
76
dsn="your-dsn-here",
77
integrations=[FlaskIntegration(transaction_style="endpoint")]
78
)
79
```
80
81
#### FastAPI Integration
82
83
```python { .api }
84
class FastApiIntegration(Integration):
85
def __init__(self, transaction_style: str = "endpoint"): ...
86
```
87
88
### Database Integrations
89
90
Automatic instrumentation for database operations with query tracking, performance monitoring, and error capture.
91
92
#### SQLAlchemy Integration
93
94
```python { .api }
95
class SqlalchemyIntegration(Integration):
96
def __init__(self): ...
97
```
98
99
**Usage:**
100
101
```python
102
import sentry_sdk
103
from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration
104
105
sentry_sdk.init(
106
dsn="your-dsn-here",
107
integrations=[SqlalchemyIntegration()]
108
)
109
110
# Automatic instrumentation for all SQLAlchemy operations
111
from sqlalchemy import create_engine
112
engine = create_engine("postgresql://user:pass@localhost/db")
113
# Database queries automatically tracked with performance data
114
```
115
116
#### AsyncPG Integration
117
118
```python { .api }
119
class AsyncPGIntegration(Integration):
120
def __init__(self): ...
121
```
122
123
#### PyMongo Integration
124
125
```python { .api }
126
class PyMongoIntegration(Integration):
127
def __init__(self): ...
128
```
129
130
### HTTP Client Integrations
131
132
Automatic instrumentation for HTTP clients with request/response tracking and distributed tracing support.
133
134
#### HTTP Client Instrumentation (via Stdlib)
135
136
HTTP client libraries like `requests` and `urllib3` are automatically instrumented through the StdlibIntegration which hooks into the standard library's `http.client` module.
137
138
#### HTTPX Integration
139
140
```python { .api }
141
class HttpxIntegration(Integration):
142
def __init__(self): ...
143
```
144
145
**Usage:**
146
147
```python
148
import sentry_sdk
149
from sentry_sdk.integrations.httpx import HttpxIntegration
150
151
sentry_sdk.init(
152
dsn="your-dsn-here",
153
integrations=[HttpxIntegration()]
154
)
155
156
import httpx
157
# HTTP requests automatically tracked with distributed tracing
158
async with httpx.AsyncClient() as client:
159
response = await client.get("https://api.example.com/data")
160
```
161
162
### Task Queue Integrations
163
164
Automatic instrumentation for background task processing with job tracking and error monitoring.
165
166
#### Celery Integration
167
168
```python { .api }
169
class CeleryIntegration(Integration):
170
def __init__(
171
self,
172
monitor_beat_tasks: bool = False,
173
propagate_traces: bool = True
174
): ...
175
```
176
177
**Usage:**
178
179
```python
180
import sentry_sdk
181
from sentry_sdk.integrations.celery import CeleryIntegration
182
183
sentry_sdk.init(
184
dsn="your-dsn-here",
185
integrations=[
186
CeleryIntegration(
187
monitor_beat_tasks=True, # Monitor periodic tasks
188
propagate_traces=True # Enable distributed tracing
189
)
190
]
191
)
192
193
# Celery tasks automatically tracked
194
from celery import Celery
195
app = Celery('tasks')
196
197
@app.task
198
def process_data(data_id):
199
# Task execution automatically monitored
200
return process(data_id)
201
```
202
203
#### RQ Integration
204
205
```python { .api }
206
class RqIntegration(Integration):
207
def __init__(self): ...
208
```
209
210
#### Arq Integration
211
212
```python { .api }
213
class ArqIntegration(Integration):
214
def __init__(self): ...
215
```
216
217
### AI/ML Library Integrations
218
219
Automatic instrumentation for AI and machine learning libraries with operation tracking and token usage monitoring.
220
221
#### OpenAI Integration
222
223
```python { .api }
224
class OpenAIIntegration(Integration):
225
def __init__(
226
self,
227
include_prompts: bool = True,
228
include_completions: bool = True
229
): ...
230
```
231
232
**Usage:**
233
234
```python
235
import sentry_sdk
236
from sentry_sdk.integrations.openai import OpenAIIntegration
237
238
sentry_sdk.init(
239
dsn="your-dsn-here",
240
integrations=[
241
OpenAIIntegration(
242
include_prompts=True, # Include prompt data in spans
243
include_completions=True # Include completion data in spans
244
)
245
]
246
)
247
248
import openai
249
# OpenAI API calls automatically tracked with token usage and timing
250
client = openai.OpenAI()
251
response = client.chat.completions.create(
252
model="gpt-3.5-turbo",
253
messages=[{"role": "user", "content": "Hello!"}]
254
)
255
```
256
257
#### Anthropic Integration
258
259
```python { .api }
260
class AnthropicIntegration(Integration):
261
def __init__(
262
self,
263
include_prompts: bool = True,
264
include_completions: bool = True
265
): ...
266
```
267
268
#### LangChain Integration
269
270
```python { .api }
271
class LangchainIntegration(Integration):
272
def __init__(self): ...
273
```
274
275
#### Hugging Face Hub Integration
276
277
```python { .api }
278
class HuggingfaceHubIntegration(Integration):
279
def __init__(self): ...
280
```
281
282
### Cloud and Infrastructure Integrations
283
284
Integrations for cloud services and infrastructure components.
285
286
#### AWS Lambda Integration
287
288
```python { .api }
289
class AwsLambdaIntegration(Integration):
290
def __init__(self, timeout_warning: bool = False): ...
291
```
292
293
#### Boto3 Integration
294
295
```python { .api }
296
class Boto3Integration(Integration):
297
def __init__(self): ...
298
```
299
300
### ASGI/WSGI Integrations
301
302
Low-level integrations for ASGI and WSGI applications.
303
304
#### ASGI Integration
305
306
```python { .api }
307
class AsgiIntegration(Integration):
308
def __init__(
309
self,
310
transaction_style: str = "endpoint",
311
middleware_spans: bool = True
312
): ...
313
```
314
315
#### WSGI Integration
316
317
```python { .api }
318
class WsgiIntegration(Integration):
319
def __init__(
320
self,
321
transaction_style: str = "endpoint"
322
): ...
323
```
324
325
### Logging Integrations
326
327
Enhanced logging with automatic error capture and log correlation.
328
329
#### Logging Integration
330
331
```python { .api }
332
class LoggingIntegration(Integration):
333
def __init__(
334
self,
335
level: int = logging.INFO,
336
event_level: int = logging.ERROR
337
): ...
338
```
339
340
**Usage:**
341
342
```python
343
import sentry_sdk
344
import logging
345
from sentry_sdk.integrations.logging import LoggingIntegration
346
347
sentry_sdk.init(
348
dsn="your-dsn-here",
349
integrations=[
350
LoggingIntegration(
351
level=logging.INFO, # Capture info and above as breadcrumbs
352
event_level=logging.ERROR # Send error and above as events
353
)
354
]
355
)
356
357
# Standard logging automatically integrated
358
logger = logging.getLogger(__name__)
359
logger.info("This becomes a breadcrumb")
360
logger.error("This becomes a Sentry event")
361
```
362
363
#### Loguru Integration
364
365
```python { .api }
366
class LoguruIntegration(Integration):
367
def __init__(self): ...
368
```
369
370
## Default Integrations
371
372
### Automatically Enabled
373
374
These integrations are enabled by default when `default_integrations=True`:
375
376
- **ArgvIntegration**: Command-line arguments capture
377
- **AtexitIntegration**: Graceful shutdown handling
378
- **DedupeIntegration**: Duplicate event prevention
379
- **ExcepthookIntegration**: Uncaught exception handling
380
- **LoggingIntegration**: Standard library logging
381
- **ModulesIntegration**: Installed packages information
382
- **StdlibIntegration**: Standard library instrumentation
383
- **ThreadingIntegration**: Threading support
384
385
### Auto-Enabling Integrations
386
387
These integrations automatically enable when their corresponding libraries are detected:
388
389
Web Frameworks: Django, Flask, FastAPI, Starlette, Sanic, Tornado, Pyramid, Bottle, Falcon, Quart, Litestar
390
391
Databases: SQLAlchemy, AsyncPG, PyMongo, Redis, ClickHouse Driver
392
393
HTTP Clients: HTTPX, AIOHTTP
394
395
Task Queues: Celery, RQ, Arq, Huey, Dramatiq
396
397
AI/ML: OpenAI, Anthropic, Cohere, LangChain, Hugging Face Hub
398
399
Cloud: AWS Lambda (Boto3)
400
401
And many more...
402
403
## Integration Configuration
404
405
### Selective Integration Control
406
407
```python
408
import sentry_sdk
409
from sentry_sdk.integrations.django import DjangoIntegration
410
from sentry_sdk.integrations.redis import RedisIntegration
411
412
sentry_sdk.init(
413
dsn="your-dsn-here",
414
# Enable only specific integrations
415
integrations=[
416
DjangoIntegration(),
417
RedisIntegration(),
418
],
419
default_integrations=False, # Disable default integrations
420
auto_enabling_integrations=False # Disable auto-detection
421
)
422
```
423
424
### Disable Specific Integrations
425
426
```python
427
import sentry_sdk
428
from sentry_sdk.integrations.httpx import HttpxIntegration
429
430
sentry_sdk.init(
431
dsn="your-dsn-here",
432
disabled_integrations=[HttpxIntegration] # Disable httpx integration
433
)
434
```
435
436
## Custom Integration Development
437
438
### Creating Custom Integrations
439
440
```python
441
from sentry_sdk.integrations import Integration
442
from sentry_sdk.utils import capture_internal_exceptions
443
444
class MyCustomIntegration(Integration):
445
identifier = "my_custom"
446
447
def __init__(self, option1=True, option2="default"):
448
self.option1 = option1
449
self.option2 = option2
450
451
@staticmethod
452
def setup_once():
453
# This method is called once when the integration is enabled
454
import my_library
455
456
original_method = my_library.important_function
457
458
def sentry_wrapped_method(*args, **kwargs):
459
with capture_internal_exceptions():
460
# Add Sentry instrumentation
461
with sentry_sdk.start_span(
462
op="my_library.operation",
463
description="important_function"
464
):
465
return original_method(*args, **kwargs)
466
467
my_library.important_function = sentry_wrapped_method
468
```
469
470
**Usage:**
471
472
```python
473
sentry_sdk.init(
474
dsn="your-dsn-here",
475
integrations=[MyCustomIntegration(option1=False, option2="custom")]
476
)
477
```
478
479
Integration capabilities provide comprehensive automatic instrumentation across the Python ecosystem, enabling detailed observability and error tracking with minimal configuration effort.