0
# Sentry Extension
1
2
Integration with Sentry SDK for tagging events with correlation IDs, enabling correlation between application logs and error monitoring. This extension automatically adds correlation IDs as transaction tags in Sentry events.
3
4
## Capabilities
5
6
### Sentry Extension Factory
7
8
Returns a function for setting Sentry transaction IDs, with automatic detection of Sentry SDK availability.
9
10
```python { .api }
11
def get_sentry_extension() -> Callable[[str], None]:
12
"""
13
Return set_transaction_id function if Sentry SDK is installed.
14
15
This factory function detects whether the Sentry SDK is available
16
and returns the appropriate function for setting correlation IDs
17
as Sentry transaction tags.
18
19
Returns:
20
- Callable[[str], None]: Function to set Sentry transaction ID
21
- If Sentry SDK is not installed, returns no-op lambda function
22
"""
23
```
24
25
The returned function can be called with correlation IDs to tag Sentry events, enabling correlation between application logs and error monitoring. If Sentry is not installed, the function gracefully returns a no-op lambda that accepts correlation IDs but performs no action.
26
27
### Transaction ID Tagging
28
29
Sets Sentry's event transaction ID as the current correlation ID, enabling correlation between logs and error events.
30
31
```python { .api }
32
def set_transaction_id(correlation_id: str) -> None:
33
"""
34
Set Sentry's event transaction ID as the current correlation ID.
35
36
The transaction ID is displayed in a Sentry event's detail view,
37
which makes it easier to correlate logs to specific events.
38
39
This function handles different Sentry SDK versions:
40
- v2.12.0+: Uses get_isolation_scope() API
41
- Earlier versions: Uses configure_scope() context manager
42
43
Parameters:
44
- correlation_id: The correlation ID to set as transaction tag
45
46
Raises:
47
- ImportError: If Sentry SDK is not installed (handled internally)
48
"""
49
```
50
51
The function automatically detects the Sentry SDK version and uses the appropriate API:
52
- **Sentry SDK 2.12.0+**: Uses the newer `get_isolation_scope()` API
53
- **Earlier versions**: Uses the legacy `configure_scope()` context manager
54
55
## Usage Examples
56
57
### Automatic Integration
58
59
```python
60
from fastapi import FastAPI
61
from asgi_correlation_id import CorrelationIdMiddleware
62
import sentry_sdk
63
64
# Initialize Sentry
65
sentry_sdk.init(
66
dsn="your-sentry-dsn",
67
traces_sample_rate=1.0,
68
)
69
70
# Add correlation middleware - Sentry integration is automatic
71
app = FastAPI()
72
app.add_middleware(CorrelationIdMiddleware)
73
74
@app.get("/error")
75
async def trigger_error():
76
# This error will be tagged with the correlation ID in Sentry
77
raise ValueError("Test error")
78
```
79
80
### Manual Sentry Tagging
81
82
```python
83
from asgi_correlation_id import correlation_id
84
from asgi_correlation_id.extensions.sentry import set_transaction_id
85
import logging
86
87
logger = logging.getLogger(__name__)
88
89
async def process_request():
90
# Get current correlation ID
91
current_id = correlation_id.get()
92
93
if current_id:
94
# Manually tag Sentry transaction
95
set_transaction_id(current_id)
96
logger.info(f"Processing request {current_id}")
97
98
try:
99
# Some processing that might fail
100
result = risky_operation()
101
return result
102
except Exception as e:
103
# Error will be correlated with logs via shared correlation ID
104
logger.error(f"Processing failed: {e}")
105
raise
106
```
107
108
### Custom Sentry Configuration
109
110
```python
111
import sentry_sdk
112
from sentry_sdk.integrations.logging import LoggingIntegration
113
from asgi_correlation_id import CorrelationIdFilter
114
115
# Configure Sentry with logging integration
116
sentry_logging = LoggingIntegration(
117
level=logging.INFO, # Capture info and above as breadcrumbs
118
event_level=logging.ERROR # Send errors as events
119
)
120
121
sentry_sdk.init(
122
dsn="your-sentry-dsn",
123
integrations=[sentry_logging],
124
traces_sample_rate=1.0,
125
)
126
127
# Add correlation ID to logs
128
correlation_filter = CorrelationIdFilter()
129
logging.getLogger().addFilter(correlation_filter)
130
131
# Now both logs and Sentry events will have correlation IDs
132
```
133
134
### Celery Integration with Sentry
135
136
```python
137
from celery import Celery
138
from asgi_correlation_id.extensions.celery import load_correlation_ids
139
from asgi_correlation_id.extensions.sentry import get_sentry_extension
140
import sentry_sdk
141
142
# Initialize Sentry for Celery workers
143
sentry_sdk.init(dsn="your-sentry-dsn")
144
145
app = Celery('tasks')
146
147
# Enable correlation ID transfer to Celery tasks
148
load_correlation_ids()
149
150
@app.task
151
def process_data(data):
152
# Correlation ID is automatically transferred from request
153
# and tagged in Sentry via the middleware integration
154
try:
155
return process(data)
156
except Exception as e:
157
# Error in Sentry will show correlation ID from originating request
158
raise
159
```
160
161
## Integration Points
162
163
### Middleware Integration
164
165
The Sentry extension is automatically loaded by `CorrelationIdMiddleware`:
166
167
```python
168
# In CorrelationIdMiddleware.__post_init__()
169
self.sentry_extension = get_sentry_extension()
170
171
# In CorrelationIdMiddleware.__call__()
172
correlation_id.set(id_value)
173
self.sentry_extension(id_value) # Automatically tag Sentry events
174
```
175
176
### Celery Integration
177
178
The Celery extension also integrates with Sentry:
179
180
```python
181
# In Celery signal handlers
182
from asgi_correlation_id.extensions.sentry import get_sentry_extension
183
184
sentry_extension = get_sentry_extension()
185
186
@task_prerun.connect(weak=False)
187
def load_correlation_id(task, **kwargs):
188
id_value = task.request.get(header_key)
189
if id_value:
190
correlation_id.set(id_value)
191
sentry_extension(id_value) # Tag Celery task events
192
```
193
194
## Sentry Event Correlation
195
196
With the extension enabled, Sentry events will include correlation IDs as transaction tags:
197
198
### In Sentry Dashboard
199
200
```
201
Event ID: abc123def456
202
Transaction ID: req-a1b2c3d4-e5f6-7890 # Your correlation ID
203
204
Breadcrumbs:
205
- INFO: Processing request req-a1b2c3d4-e5f6-7890
206
- ERROR: Database connection failed
207
208
Tags:
209
- transaction_id: req-a1b2c3d4-e5f6-7890
210
- environment: production
211
```
212
213
### Log Correlation
214
215
With both correlation logging and Sentry integration:
216
217
```
218
# Application logs
219
2023-01-01 12:00:00 INFO [req-a1b2c3d4] Processing user request
220
2023-01-01 12:00:01 ERROR [req-a1b2c3d4] Database connection failed
221
222
# Sentry event tagged with: transaction_id=req-a1b2c3d4
223
# Easy to correlate the Sentry error with application logs
224
```
225
226
## Version Compatibility
227
228
The extension handles different Sentry SDK versions automatically:
229
230
### Sentry SDK 2.12.0+
231
232
```python
233
# Uses newer isolation scope API
234
scope = sentry_sdk.get_isolation_scope()
235
scope.set_tag('transaction_id', correlation_id)
236
```
237
238
### Sentry SDK < 2.12.0
239
240
```python
241
# Uses legacy configure_scope API
242
with sentry_sdk.configure_scope() as scope:
243
scope.set_tag('transaction_id', correlation_id)
244
```
245
246
The version detection is handled automatically using the `packaging` library to parse the Sentry SDK version.
247
248
## Types
249
250
```python { .api }
251
from typing import Callable
252
from packaging import version
253
254
# Type definitions
255
SentryExtension = Callable[[str], None]
256
NoOpExtension = Callable[[str], None]
257
```