0
# Structured Logging
1
2
OpenTelemetry-compatible structured logging interface with automatic correlation to Sentry events, performance data, and comprehensive context propagation for debugging and observability.
3
4
## Capabilities
5
6
### Structured Logging Functions
7
8
Send structured log messages with automatic correlation to Sentry events and spans using OpenTelemetry-compatible logging interfaces.
9
10
```python { .api }
11
def trace(template: str, **kwargs) -> None:
12
"""
13
Send a trace-level structured log message.
14
15
Parameters:
16
- template: Log message template with placeholder formatting
17
- **kwargs: Structured data to include in log context
18
"""
19
20
def debug(template: str, **kwargs) -> None:
21
"""
22
Send a debug-level structured log message.
23
24
Parameters:
25
- template: Log message template with placeholder formatting
26
- **kwargs: Structured data to include in log context
27
"""
28
29
def info(template: str, **kwargs) -> None:
30
"""
31
Send an info-level structured log message.
32
33
Parameters:
34
- template: Log message template with placeholder formatting
35
- **kwargs: Structured data to include in log context
36
"""
37
38
def warning(template: str, **kwargs) -> None:
39
"""
40
Send a warning-level structured log message.
41
42
Parameters:
43
- template: Log message template with placeholder formatting
44
- **kwargs: Structured data to include in log context
45
"""
46
47
def error(template: str, **kwargs) -> None:
48
"""
49
Send an error-level structured log message.
50
51
Parameters:
52
- template: Log message template with placeholder formatting
53
- **kwargs: Structured data to include in log context
54
"""
55
56
def fatal(template: str, **kwargs) -> None:
57
"""
58
Send a fatal-level structured log message.
59
60
Parameters:
61
- template: Log message template with placeholder formatting
62
- **kwargs: Structured data to include in log context
63
"""
64
```
65
66
**Usage Examples:**
67
68
```python
69
import sentry_sdk
70
71
# Initialize SDK first
72
sentry_sdk.init(dsn="your-dsn-here")
73
74
# Simple structured logging
75
sentry_sdk.logger.info("User login successful", user_id="user_123")
76
sentry_sdk.logger.warning("High memory usage detected", memory_percent=85.2)
77
sentry_sdk.logger.error("Database connection failed",
78
host="db.example.com",
79
port=5432,
80
timeout=30)
81
82
# Template-based logging with structured data
83
sentry_sdk.logger.info(
84
"Processing order {order_id} for user {user_id}",
85
order_id="order_456",
86
user_id="user_123",
87
item_count=3,
88
total_amount=99.99
89
)
90
91
# Debug logging with complex structured data
92
sentry_sdk.logger.debug(
93
"Cache operation completed",
94
operation="get",
95
key="user_prefs:123",
96
hit=True,
97
latency_ms=1.2,
98
cache_size=1024,
99
metadata={
100
"region": "us-west-2",
101
"cluster": "cache-cluster-1"
102
}
103
)
104
105
# Error logging with context
106
def process_payment(payment_data):
107
try:
108
result = payment_processor.charge(payment_data)
109
sentry_sdk.logger.info(
110
"Payment processed successfully",
111
transaction_id=result.id,
112
amount=payment_data.amount,
113
currency=payment_data.currency,
114
processing_time_ms=result.processing_time
115
)
116
return result
117
except PaymentError as e:
118
sentry_sdk.logger.error(
119
"Payment processing failed",
120
error_code=e.code,
121
error_message=str(e),
122
payment_method=payment_data.method,
123
amount=payment_data.amount,
124
retry_count=e.retry_count
125
)
126
raise
127
```
128
129
## Automatic Correlation
130
131
### Event Correlation
132
133
Structured logs automatically correlate with Sentry events and performance data:
134
135
- **Trace Correlation**: Logs include trace and span IDs when called within transactions
136
- **Event Context**: Logs inherit scope context (user, tags, extra data)
137
- **Error Association**: Error-level logs create Sentry events with structured data
138
- **Performance Integration**: Logs within spans include performance context
139
140
```python
141
import sentry_sdk
142
143
def process_user_request(user_id):
144
with sentry_sdk.start_transaction(name="process_request", op="function"):
145
# These logs will include transaction and span context
146
sentry_sdk.logger.info("Starting request processing", user_id=user_id)
147
148
with sentry_sdk.start_span(op="db.query", description="fetch user"):
149
user = get_user(user_id)
150
sentry_sdk.logger.debug("User data retrieved",
151
user_id=user_id,
152
user_type=user.type)
153
154
# Error logs automatically create Sentry events
155
if not user.is_active:
156
sentry_sdk.logger.error("Inactive user attempted access",
157
user_id=user_id,
158
account_status=user.status,
159
last_active=user.last_active)
160
raise UserInactiveError()
161
162
sentry_sdk.logger.info("Request processing completed",
163
user_id=user_id,
164
processing_time_ms=get_processing_time())
165
```
166
167
### Scope Integration
168
169
Structured logs inherit and can modify scope context:
170
171
```python
172
# Set structured logging context at scope level
173
sentry_sdk.set_tag("component", "payment_processor")
174
sentry_sdk.set_extra("version", "2.1.0")
175
176
# All subsequent logs include scope context
177
sentry_sdk.logger.info("Service started") # Includes component tag and version extra
178
179
# Temporarily modify context for specific logs
180
with sentry_sdk.new_scope() as scope:
181
scope.set_tag("operation", "batch_process")
182
sentry_sdk.logger.info("Batch processing started", batch_size=1000)
183
# Log includes both component and operation tags
184
```
185
186
## Configuration Integration
187
188
### Log Level Control
189
190
Structured logging respects Sentry SDK configuration:
191
192
```python
193
import sentry_sdk
194
from sentry_sdk.integrations.logging import LoggingIntegration
195
196
# Configure structured logging behavior
197
sentry_sdk.init(
198
dsn="your-dsn-here",
199
integrations=[
200
LoggingIntegration(
201
level=logging.INFO, # Breadcrumb level
202
event_level=logging.ERROR # Event creation level
203
)
204
],
205
debug=True # Enable debug-level structured logs
206
)
207
208
# Structured logs follow the configured levels
209
sentry_sdk.logger.debug("Debug info") # Only sent if debug=True
210
sentry_sdk.logger.info("Info message") # Becomes breadcrumb
211
sentry_sdk.logger.error("Error occurred") # Creates Sentry event
212
```
213
214
### Custom Log Processing
215
216
```python
217
def custom_log_processor(record):
218
"""Custom processor for structured log records."""
219
# Add custom fields to all structured logs
220
record.update({
221
"service": "payment-api",
222
"environment": "production",
223
"timestamp": datetime.utcnow().isoformat()
224
})
225
return record
226
227
# Apply custom processing (conceptual - actual implementation may vary)
228
sentry_sdk.logger.add_processor(custom_log_processor)
229
230
# All structured logs now include custom fields
231
sentry_sdk.logger.info("Operation completed", operation_id="op_123")
232
```
233
234
## Advanced Usage
235
236
### Performance Logging
237
238
Combine structured logging with performance monitoring:
239
240
```python
241
import time
242
import sentry_sdk
243
244
def monitored_operation(operation_name):
245
start_time = time.time()
246
247
sentry_sdk.logger.info("Operation starting", operation=operation_name)
248
249
with sentry_sdk.start_span(op="custom", description=operation_name) as span:
250
try:
251
# Perform operation
252
result = perform_complex_operation()
253
254
duration = time.time() - start_time
255
span.set_measurement("operation_duration", duration * 1000, "millisecond")
256
257
sentry_sdk.logger.info(
258
"Operation completed successfully",
259
operation=operation_name,
260
duration_ms=duration * 1000,
261
result_size=len(result)
262
)
263
264
return result
265
266
except Exception as e:
267
duration = time.time() - start_time
268
269
sentry_sdk.logger.error(
270
"Operation failed",
271
operation=operation_name,
272
duration_ms=duration * 1000,
273
error_type=type(e).__name__,
274
error_message=str(e)
275
)
276
raise
277
```
278
279
### Business Logic Logging
280
281
Use structured logging for business intelligence and monitoring:
282
283
```python
284
def track_business_metrics(user_action, **metrics):
285
"""Track business metrics with structured logging."""
286
sentry_sdk.logger.info(
287
f"Business metric: {user_action}",
288
metric_type="business_event",
289
action=user_action,
290
timestamp=datetime.utcnow().isoformat(),
291
**metrics
292
)
293
294
# Usage examples
295
track_business_metrics("user_signup",
296
user_type="premium",
297
referral_source="google_ads",
298
trial_length_days=14)
299
300
track_business_metrics("purchase_completed",
301
amount=99.99,
302
currency="USD",
303
product_category="software",
304
payment_method="credit_card")
305
306
track_business_metrics("feature_usage",
307
feature="advanced_analytics",
308
usage_duration_minutes=45,
309
user_tier="enterprise")
310
```
311
312
## Best Practices
313
314
### Message Templates
315
316
Use consistent, searchable message templates:
317
318
```python
319
# Good: Consistent templates
320
sentry_sdk.logger.info("User action: {action}", action="login", user_id="123")
321
sentry_sdk.logger.info("User action: {action}", action="logout", user_id="123")
322
323
# Avoid: Variable messages that can't be grouped
324
sentry_sdk.logger.info(f"User {user_id} performed {action}") # Hard to search/group
325
```
326
327
### Structured Data Organization
328
329
Organize structured data consistently:
330
331
```python
332
# Good: Consistent field naming and organization
333
sentry_sdk.logger.info("Database operation completed",
334
db_operation="select",
335
db_table="users",
336
db_duration_ms=45,
337
db_rows_affected=1,
338
query_hash="abc123")
339
340
# Use nested structures for complex data
341
sentry_sdk.logger.info("API request processed",
342
request={
343
"method": "POST",
344
"path": "/api/users",
345
"duration_ms": 125
346
},
347
response={
348
"status_code": 200,
349
"size_bytes": 1024
350
})
351
```
352
353
### Log Level Guidelines
354
355
- **trace**: Very detailed debugging information
356
- **debug**: Development and troubleshooting information
357
- **info**: Normal application flow and business events
358
- **warning**: Concerning situations that don't prevent operation
359
- **error**: Error conditions that should be investigated
360
- **fatal**: Critical failures that may cause application termination
361
362
Structured logging provides comprehensive observability with automatic correlation to Sentry's error tracking and performance monitoring capabilities.