0
# Event Capture
1
2
Manual and automatic capture of exceptions, messages, and custom events with context preservation, filtering capabilities, and detailed metadata attachment.
3
4
## Capabilities
5
6
### Exception Capture
7
8
Capture exceptions with full stack traces, local variables, and contextual information for debugging and error tracking.
9
10
```python { .api }
11
def capture_exception(
12
error: Optional[BaseException] = None,
13
scope: Optional[Scope] = None,
14
**scope_kwargs
15
) -> Optional[str]:
16
"""
17
Capture an exception and send it to Sentry.
18
19
Parameters:
20
- error: Exception instance to capture (if None, captures current exception)
21
- scope: Scope to use for this event (if None, uses current scope)
22
- **scope_kwargs: Additional scope data (tags, extra, user, level, fingerprint)
23
24
Returns:
25
str: Event ID if event was sent, None if filtered or dropped
26
"""
27
```
28
29
**Usage Examples:**
30
31
```python
32
import sentry_sdk
33
34
# Capture current exception in except block
35
try:
36
risky_operation()
37
except Exception:
38
# Automatically captures current exception with full context
39
event_id = sentry_sdk.capture_exception()
40
print(f"Error reported with ID: {event_id}")
41
42
# Capture specific exception with additional context
43
try:
44
process_user_data(user_id=123)
45
except ValueError as e:
46
event_id = sentry_sdk.capture_exception(
47
e,
48
tags={"component": "data_processor"},
49
extra={"user_id": 123, "operation": "data_processing"},
50
level="error"
51
)
52
53
# Capture exception outside of except block
54
def process_file(filename):
55
try:
56
return parse_file(filename)
57
except Exception as e:
58
# Capture and re-raise
59
sentry_sdk.capture_exception(e)
60
raise
61
```
62
63
### Message Capture
64
65
Capture log messages and custom events with structured data and severity levels for application monitoring.
66
67
```python { .api }
68
def capture_message(
69
message: str,
70
level: Optional[Union[str, LogLevel]] = None,
71
scope: Optional[Scope] = None,
72
**scope_kwargs
73
) -> Optional[str]:
74
"""
75
Capture a message and send it to Sentry.
76
77
Parameters:
78
- message: Message text to capture
79
- level: Log level ('debug', 'info', 'warning', 'error', 'fatal')
80
- scope: Scope to use for this event (if None, uses current scope)
81
- **scope_kwargs: Additional scope data (tags, extra, user, fingerprint)
82
83
Returns:
84
str: Event ID if event was sent, None if filtered or dropped
85
"""
86
```
87
88
**Usage Examples:**
89
90
```python
91
import sentry_sdk
92
93
# Simple message capture
94
sentry_sdk.capture_message("User logged in successfully")
95
96
# Message with level and context
97
sentry_sdk.capture_message(
98
"Payment processing failed",
99
level="error",
100
tags={"payment_method": "credit_card"},
101
extra={
102
"user_id": "user_123",
103
"amount": 99.99,
104
"currency": "USD",
105
"error_code": "CARD_DECLINED"
106
}
107
)
108
109
# Critical system message
110
sentry_sdk.capture_message(
111
"Database connection pool exhausted",
112
level="fatal",
113
tags={"component": "database", "severity": "critical"},
114
fingerprint=["database", "connection-pool"]
115
)
116
```
117
118
### Custom Event Capture
119
120
Capture arbitrary events with full control over event structure, metadata, and processing for advanced use cases.
121
122
```python { .api }
123
def capture_event(
124
event: Dict[str, Any],
125
hint: Optional[Dict[str, Any]] = None,
126
scope: Optional[Scope] = None,
127
**scope_kwargs
128
) -> Optional[str]:
129
"""
130
Capture a custom event and send it to Sentry.
131
132
Parameters:
133
- event: Event dictionary with message, level, and other properties
134
- hint: Processing hints for event processors
135
- scope: Scope to use for this event (if None, uses current scope)
136
- **scope_kwargs: Additional scope data (tags, extra, user, level, fingerprint)
137
138
Returns:
139
str: Event ID if event was sent, None if filtered or dropped
140
"""
141
```
142
143
**Usage Examples:**
144
145
```python
146
import sentry_sdk
147
148
# Custom structured event
149
event = {
150
"message": "Custom business logic event",
151
"level": "info",
152
"extra": {
153
"business_process": "order_fulfillment",
154
"step": "inventory_check",
155
"result": "success",
156
"processing_time_ms": 145
157
},
158
"tags": {
159
"service": "inventory",
160
"region": "us-west-2"
161
}
162
}
163
164
event_id = sentry_sdk.capture_event(event)
165
166
# Event with processing hints
167
custom_event = {
168
"message": "Security audit event",
169
"level": "warning",
170
"logger": "security.audit",
171
"extra": {
172
"action": "permission_denied",
173
"resource": "/admin/users",
174
"ip_address": "192.168.1.100"
175
}
176
}
177
178
hint = {
179
"should_capture": True,
180
"security_event": True
181
}
182
183
sentry_sdk.capture_event(custom_event, hint=hint)
184
```
185
186
## Event Properties
187
188
### Event Structure
189
190
Events sent to Sentry follow a standard structure with these key fields:
191
192
- **message**: Human-readable description
193
- **level**: Severity level (trace, debug, info, warning, error, fatal)
194
- **logger**: Logger name or component identifier
195
- **platform**: Platform identifier (python)
196
- **timestamp**: Event occurrence time
197
- **extra**: Additional metadata as key-value pairs
198
- **tags**: Indexed metadata for filtering and searching
199
- **user**: User context information
200
- **request**: HTTP request data (when available)
201
- **contexts**: Structured context objects (os, runtime, etc.)
202
- **breadcrumbs**: Trail of events leading to the error
203
- **fingerprint**: Custom grouping rules for the event
204
205
### Scope Integration
206
207
All capture functions inherit context from the current scope and support scope keyword arguments:
208
209
- **tags**: Key-value pairs for filtering (`tags={"component": "auth"}`)
210
- **extra**: Additional debug information (`extra={"user_id": 123}`)
211
- **user**: User identification (`user={"id": "123", "email": "user@example.com"}`)
212
- **level**: Override event severity (`level="error"`)
213
- **fingerprint**: Custom grouping (`fingerprint=["auth", "login-failed"]`)
214
215
### Automatic Context
216
217
The SDK automatically includes:
218
219
- **Stack traces**: For exceptions and when `attach_stacktrace=True`
220
- **Local variables**: When debug mode is enabled
221
- **Request data**: From web framework integrations
222
- **System context**: OS, runtime, and hardware information
223
- **Breadcrumbs**: Automatic trail from integrations and manual additions
224
225
## Error Handling
226
227
All capture functions are designed to never raise exceptions themselves, ensuring application stability:
228
229
```python
230
# These calls are safe even if Sentry is misconfigured
231
sentry_sdk.capture_exception() # Returns None if disabled/failed
232
sentry_sdk.capture_message("test") # Returns None if disabled/failed
233
sentry_sdk.capture_event({}) # Returns None if disabled/failed
234
```
235
236
Events may be filtered or dropped due to:
237
- SDK not initialized
238
- Rate limiting
239
- Sampling configuration
240
- `before_send` filters
241
- Network connectivity issues
242
243
The return value indicates whether the event was successfully queued for sending (returns event ID) or filtered/dropped (returns None).