0
# Context and Metadata
1
2
Setting user information, tags, extra data, context objects, and breadcrumbs for enhanced debugging, event correlation, and structured data organization.
3
4
## Capabilities
5
6
### User Information
7
8
Associate user data with events for user-centric error tracking and debugging with support for multiple identification schemes.
9
10
```python { .api }
11
def set_user(value: Optional[Dict[str, Any]]) -> None:
12
"""
13
Set user information for all subsequent events.
14
15
Parameters:
16
- value: User data dictionary or None to clear user data
17
Common fields: id, email, username, ip_address, name, segment
18
"""
19
```
20
21
**Usage Examples:**
22
23
```python
24
import sentry_sdk
25
26
# Basic user identification
27
sentry_sdk.set_user({
28
"id": "user_123",
29
"email": "user@example.com",
30
"username": "johndoe"
31
})
32
33
# Comprehensive user context
34
sentry_sdk.set_user({
35
"id": "user_123",
36
"email": "user@example.com",
37
"username": "johndoe",
38
"name": "John Doe",
39
"ip_address": "192.168.1.100",
40
"segment": "premium",
41
"subscription": "pro",
42
"signup_date": "2023-01-15",
43
"last_login": "2024-09-06T10:30:00Z"
44
})
45
46
# Clear user data (e.g., on logout)
47
sentry_sdk.set_user(None)
48
49
# Anonymous user with limited context
50
sentry_sdk.set_user({
51
"id": "anonymous_456",
52
"ip_address": "10.0.0.50",
53
"segment": "trial"
54
})
55
```
56
57
### Tags
58
59
Set indexed metadata for filtering, searching, and organizing events in the Sentry interface.
60
61
```python { .api }
62
def set_tag(key: str, value: str) -> None:
63
"""
64
Set a single tag for event filtering and grouping.
65
66
Parameters:
67
- key: Tag name (max 32 characters)
68
- value: Tag value (max 200 characters, converted to string)
69
"""
70
71
def set_tags(tags: Dict[str, str]) -> None:
72
"""
73
Set multiple tags at once.
74
75
Parameters:
76
- tags: Dictionary of tag key-value pairs
77
"""
78
```
79
80
**Usage Examples:**
81
82
```python
83
import sentry_sdk
84
85
# Single tag
86
sentry_sdk.set_tag("environment", "production")
87
sentry_sdk.set_tag("version", "1.2.3")
88
sentry_sdk.set_tag("feature_flag", "new_checkout")
89
90
# Multiple tags
91
sentry_sdk.set_tags({
92
"service": "payment-processor",
93
"region": "us-west-2",
94
"datacenter": "aws",
95
"cluster": "prod-cluster-1",
96
"component": "billing"
97
})
98
99
# Request-specific tags (often set by framework integrations)
100
sentry_sdk.set_tags({
101
"http.method": "POST",
102
"endpoint": "/api/v1/payments",
103
"user_type": "premium",
104
"api_version": "v1"
105
})
106
107
# Business context tags
108
sentry_sdk.set_tags({
109
"tenant": "acme_corp",
110
"subscription_tier": "enterprise",
111
"feature_set": "advanced",
112
"ab_test_group": "variant_b"
113
})
114
```
115
116
### Extra Data
117
118
Set additional debugging information that provides detailed context for troubleshooting events.
119
120
```python { .api }
121
def set_extra(key: str, value: Any) -> None:
122
"""
123
Set extra debugging information for events.
124
125
Parameters:
126
- key: Extra data key name
127
- value: Any serializable value (dict, list, string, number, etc.)
128
"""
129
```
130
131
**Usage Examples:**
132
133
```python
134
import sentry_sdk
135
136
# Simple key-value data
137
sentry_sdk.set_extra("request_id", "req_abc123")
138
sentry_sdk.set_extra("processing_time_ms", 245)
139
sentry_sdk.set_extra("retry_count", 3)
140
141
# Complex structured data
142
sentry_sdk.set_extra("request_payload", {
143
"user_id": 123,
144
"action": "create_order",
145
"items": [
146
{"product_id": "prod_1", "quantity": 2},
147
{"product_id": "prod_2", "quantity": 1}
148
],
149
"total_amount": 99.99,
150
"currency": "USD"
151
})
152
153
# Configuration and environment details
154
sentry_sdk.set_extra("database_config", {
155
"host": "db.example.com",
156
"port": 5432,
157
"database": "production",
158
"pool_size": 10,
159
"connection_timeout": 30
160
})
161
162
# Performance and resource data
163
sentry_sdk.set_extra("system_metrics", {
164
"cpu_usage": 45.2,
165
"memory_usage_mb": 1024,
166
"disk_free_gb": 50.5,
167
"active_connections": 25
168
})
169
```
170
171
### Context Objects
172
173
Set structured context data organized by context type for comprehensive environmental information.
174
175
```python { .api }
176
def set_context(key: str, value: Dict[str, Any]) -> None:
177
"""
178
Set structured context information by category.
179
180
Parameters:
181
- key: Context category name (e.g., 'os', 'runtime', 'device', 'app')
182
- value: Context data dictionary
183
"""
184
```
185
186
**Usage Examples:**
187
188
```python
189
import sentry_sdk
190
191
# Application context
192
sentry_sdk.set_context("app", {
193
"name": "payment-service",
194
"version": "2.1.4",
195
"build_number": "1847",
196
"commit_sha": "a1b2c3d4",
197
"environment": "production",
198
"region": "us-west-2"
199
})
200
201
# Runtime context
202
sentry_sdk.set_context("runtime", {
203
"name": "python",
204
"version": "3.11.5",
205
"implementation": "cpython",
206
"build": "Python 3.11.5 (main, Aug 24 2023, 15:18:16)",
207
"thread_count": 12,
208
"gc_count": [145, 23, 2]
209
})
210
211
# Device/server context
212
sentry_sdk.set_context("device", {
213
"type": "server",
214
"arch": "x86_64",
215
"cpu_count": 8,
216
"memory_size": 16777216, # bytes
217
"storage_size": 107374182400, # bytes
218
"timezone": "UTC"
219
})
220
221
# Custom business context
222
sentry_sdk.set_context("business", {
223
"tenant_id": "tenant_123",
224
"organization": "Acme Corp",
225
"subscription": "enterprise",
226
"feature_flags": ["new_ui", "advanced_analytics"],
227
"experiment_groups": ["checkout_v2", "pricing_test_b"]
228
})
229
230
# Request context (typically set by web framework integrations)
231
sentry_sdk.set_context("request", {
232
"method": "POST",
233
"url": "https://api.example.com/v1/orders",
234
"query_string": "include_details=true",
235
"headers": {
236
"content-type": "application/json",
237
"user-agent": "MyApp/1.0",
238
"x-request-id": "req_abc123"
239
}
240
})
241
```
242
243
### Breadcrumbs
244
245
Add trail of events leading up to an error or event for debugging context and timeline reconstruction.
246
247
```python { .api }
248
def add_breadcrumb(
249
crumb: Optional[Dict[str, Any]] = None,
250
hint: Optional[Dict[str, Any]] = None,
251
**kwargs
252
) -> None:
253
"""
254
Add a breadcrumb to the trail of events.
255
256
Parameters:
257
- crumb: Breadcrumb dictionary with message, level, category, data, etc.
258
- hint: Processing hints for breadcrumb filters
259
- **kwargs: Breadcrumb properties as keyword arguments
260
"""
261
```
262
263
**Usage Examples:**
264
265
```python
266
import sentry_sdk
267
268
# Simple message breadcrumb
269
sentry_sdk.add_breadcrumb(
270
message="User started checkout process",
271
level="info"
272
)
273
274
# Detailed breadcrumb with category and data
275
sentry_sdk.add_breadcrumb(
276
message="Database query executed",
277
category="db",
278
level="info",
279
data={
280
"query": "SELECT * FROM orders WHERE user_id = %s",
281
"duration_ms": 45,
282
"rows_affected": 1
283
}
284
)
285
286
# HTTP request breadcrumb
287
sentry_sdk.add_breadcrumb(
288
message="API call to payment service",
289
category="http",
290
level="info",
291
data={
292
"url": "https://payments.example.com/v1/charge",
293
"method": "POST",
294
"status_code": 200,
295
"response_time_ms": 250
296
}
297
)
298
299
# Navigation breadcrumb (for web apps)
300
sentry_sdk.add_breadcrumb(
301
message="User navigated to orders page",
302
category="navigation",
303
level="info",
304
data={
305
"from": "/dashboard",
306
"to": "/orders",
307
"trigger": "menu_click"
308
}
309
)
310
311
# User action breadcrumb
312
sentry_sdk.add_breadcrumb(
313
message="Form submitted",
314
category="user",
315
level="info",
316
data={
317
"form": "checkout_form",
318
"fields": ["email", "payment_method", "billing_address"],
319
"validation_errors": []
320
}
321
)
322
323
# System event breadcrumb
324
sentry_sdk.add_breadcrumb(
325
message="Cache miss for user preferences",
326
category="cache",
327
level="warning",
328
data={
329
"key": "user_prefs_123",
330
"ttl_remaining": 0,
331
"hit_rate": 0.85
332
}
333
)
334
335
# Using kwargs for simple breadcrumbs
336
sentry_sdk.add_breadcrumb(
337
message="Configuration loaded",
338
category="config",
339
level="debug",
340
config_source="environment_variables",
341
config_count=25
342
)
343
```
344
345
## Breadcrumb Categories
346
347
### Standard Categories
348
349
- **default**: General application events
350
- **auth**: Authentication and authorization events
351
- **navigation**: Page/route changes and navigation
352
- **http**: HTTP requests and responses
353
- **db**: Database operations and queries
354
- **cache**: Cache operations (hits, misses, invalidation)
355
- **rpc**: Remote procedure calls and API interactions
356
- **user**: User actions and interactions
357
- **ui**: User interface events and state changes
358
- **system**: System-level events and resource usage
359
360
### Breadcrumb Levels
361
362
- **fatal**: Critical system failures
363
- **error**: Error conditions
364
- **warning**: Warning conditions
365
- **info**: Informational messages (default)
366
- **debug**: Debug information
367
368
## Data Organization Best Practices
369
370
### Tags vs Extra vs Context
371
372
**Use Tags for:**
373
- Filterable, searchable metadata
374
- Short string values (max 200 characters)
375
- Grouping and categorization
376
- Performance-critical indexing
377
378
**Use Extra for:**
379
- Detailed debugging information
380
- Complex data structures
381
- Large data that doesn't need indexing
382
- Request/response payloads
383
384
**Use Context for:**
385
- Structured environmental data
386
- Organized by logical categories
387
- Standard context types (app, runtime, device, etc.)
388
- Data that needs specific formatting in UI
389
390
### Scope-Level Data Setting
391
392
```python
393
# Global scope: Application-wide data
394
global_scope = sentry_sdk.get_global_scope()
395
global_scope.set_tag("service", "payment-processor")
396
global_scope.set_context("app", {"version": "1.2.3"})
397
398
# Isolation scope: Request/user-specific data
399
isolation_scope = sentry_sdk.get_isolation_scope()
400
isolation_scope.set_user({"id": "user_123"})
401
isolation_scope.set_tag("request_id", "req_456")
402
403
# Current scope: Local context data
404
current_scope = sentry_sdk.get_current_scope()
405
current_scope.set_extra("operation", "process_payment")
406
current_scope.add_breadcrumb(message="Payment validation started")
407
```
408
409
## Metadata Inheritance
410
411
Context, tags, and extra data follow scope inheritance rules:
412
1. Global scope data applies to all events
413
2. Isolation scope data applies to current request/user context
414
3. Current scope data applies to local operations
415
4. Event-specific data takes highest precedence
416
5. Child scopes inherit parent data but can override values
417
418
This hierarchical system ensures proper context isolation while maintaining comprehensive debugging information across all events and performance monitoring data.