-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_example.py
More file actions
525 lines (415 loc) · 15.5 KB
/
python_example.py
File metadata and controls
525 lines (415 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#!/usr/bin/env python3
"""
Bugsink/Sentry SDK Integration Example for Python
==================================================
This example demonstrates comprehensive error tracking integration
using the Sentry SDK with a self-hosted Bugsink server.
Requirements:
pip install sentry-sdk flask requests
DSN Format:
https://<project-key>@<your-bugsink-host>/<project-id>
"""
import os
import sys
import logging
from datetime import datetime
from functools import wraps
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration
from sentry_sdk.integrations.threading import ThreadingIntegration
# =============================================================================
# CONFIGURATION
# =============================================================================
# Get DSN from environment variable or use placeholder
SENTRY_DSN = os.getenv(
"SENTRY_DSN",
"https://your-project-key@errors.observability.app.bauer-group.com/1"
)
# Environment configuration
ENVIRONMENT = os.getenv("ENVIRONMENT", "development")
RELEASE = os.getenv("APP_VERSION", "1.0.0")
SERVER_NAME = os.getenv("HOSTNAME", "unknown")
# =============================================================================
# SENTRY INITIALIZATION
# =============================================================================
def init_sentry():
"""
Initialize Sentry SDK with comprehensive configuration.
Call this once at application startup.
"""
# Configure logging integration
logging_integration = LoggingIntegration(
level=logging.INFO, # Capture INFO and above as breadcrumbs
event_level=logging.ERROR # Send ERROR and above as events
)
sentry_sdk.init(
dsn=SENTRY_DSN,
# Environment & Release
environment=ENVIRONMENT,
release=f"my-app@{RELEASE}",
server_name=SERVER_NAME,
# Integrations
integrations=[
logging_integration,
ThreadingIntegration(propagate_hub=True),
],
# Performance Monitoring
traces_sample_rate=1.0, # 100% in dev, reduce in production (e.g., 0.1)
profiles_sample_rate=0.1, # Profile 10% of transactions
# Error Sampling
sample_rate=1.0, # Send 100% of errors
# Data Handling
send_default_pii=False, # Don't send PII by default
max_breadcrumbs=50,
attach_stacktrace=True,
# Request Data
max_request_body_size="medium", # "small", "medium", "always", "never"
# Before Send Hook - sanitize/filter events
before_send=before_send_handler,
# Before Breadcrumb Hook
before_breadcrumb=before_breadcrumb_handler,
# Debug mode (disable in production)
debug=ENVIRONMENT == "development",
)
# Set global tags
sentry_sdk.set_tag("app.component", "backend")
sentry_sdk.set_tag("app.team", "platform")
print(f"Sentry initialized for environment: {ENVIRONMENT}")
def before_send_handler(event, hint):
"""
Process events before sending to Sentry.
Use this to sanitize sensitive data or filter events.
"""
# Example: Remove sensitive headers
if "request" in event and "headers" in event["request"]:
headers = event["request"]["headers"]
sensitive_headers = ["Authorization", "Cookie", "X-API-Key"]
for header in sensitive_headers:
if header in headers:
headers[header] = "[REDACTED]"
# Example: Filter out specific exceptions
if "exception" in event:
for exception in event["exception"].get("values", []):
# Don't send expected/handled exceptions
if exception.get("type") == "ExpectedBusinessException":
return None
# Example: Add custom fingerprint for grouping
if "exception" in event:
exc_type = event["exception"]["values"][0].get("type", "")
if exc_type == "DatabaseConnectionError":
event["fingerprint"] = ["database-connection-error"]
return event
def before_breadcrumb_handler(breadcrumb, hint):
"""
Process breadcrumbs before adding to the event.
Use this to filter or sanitize breadcrumb data.
"""
# Filter out noisy breadcrumbs
if breadcrumb.get("category") == "httplib" and "/health" in breadcrumb.get("data", {}).get("url", ""):
return None
# Sanitize SQL queries
if breadcrumb.get("category") == "query":
message = breadcrumb.get("message", "")
if "password" in message.lower():
breadcrumb["message"] = "[QUERY REDACTED - CONTAINS SENSITIVE DATA]"
return breadcrumb
# =============================================================================
# CONTEXT MANAGEMENT
# =============================================================================
def set_user_context(user_id: str, email: str = None, username: str = None,
ip_address: str = None, **extra):
"""
Set user context for error tracking.
Call this after user authentication.
"""
user_data = {"id": user_id}
if email:
user_data["email"] = email
if username:
user_data["username"] = username
if ip_address:
user_data["ip_address"] = ip_address
# Add any extra user data
user_data.update(extra)
sentry_sdk.set_user(user_data)
def clear_user_context():
"""Clear user context (e.g., on logout)."""
sentry_sdk.set_user(None)
def add_breadcrumb(message: str, category: str = "custom", level: str = "info",
data: dict = None):
"""
Add a breadcrumb to track user actions/events.
Breadcrumbs help understand what happened before an error.
"""
sentry_sdk.add_breadcrumb(
message=message,
category=category,
level=level,
data=data or {},
timestamp=datetime.now()
)
# =============================================================================
# ERROR CAPTURING
# =============================================================================
def capture_exception(exception: Exception = None, **extra_context):
"""
Capture an exception with optional extra context.
Args:
exception: The exception to capture (or None to capture current)
**extra_context: Additional context to attach
"""
with sentry_sdk.push_scope() as scope:
# Add extra context
for key, value in extra_context.items():
scope.set_extra(key, value)
if exception:
sentry_sdk.capture_exception(exception)
else:
sentry_sdk.capture_exception()
def capture_message(message: str, level: str = "info", **extra_context):
"""
Capture a message (non-exception event).
Args:
message: The message to capture
level: Severity level (debug, info, warning, error, fatal)
**extra_context: Additional context to attach
"""
with sentry_sdk.push_scope() as scope:
for key, value in extra_context.items():
scope.set_extra(key, value)
sentry_sdk.capture_message(message, level=level)
# =============================================================================
# DECORATORS
# =============================================================================
def track_errors(operation_name: str = None):
"""
Decorator to automatically track errors in a function.
Usage:
@track_errors("user_registration")
def register_user(email, password):
...
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
op_name = operation_name or func.__name__
with sentry_sdk.push_scope() as scope:
scope.set_tag("operation", op_name)
scope.set_extra("function", func.__name__)
scope.set_extra("args_count", len(args))
add_breadcrumb(
message=f"Executing {op_name}",
category="function",
level="info"
)
try:
return func(*args, **kwargs)
except Exception as e:
scope.set_extra("error_type", type(e).__name__)
raise
return wrapper
return decorator
def transaction(name: str, op: str = "function"):
"""
Decorator to create a transaction for performance monitoring.
Usage:
@transaction("process_order", op="task")
def process_order(order_id):
...
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
with sentry_sdk.start_transaction(name=name, op=op) as txn:
try:
return func(*args, **kwargs)
except Exception:
txn.set_status("internal_error")
raise
else:
txn.set_status("ok")
return wrapper
return decorator
# =============================================================================
# FLASK INTEGRATION EXAMPLE
# =============================================================================
def create_flask_app():
"""
Example Flask application with Sentry integration.
"""
try:
from flask import Flask, request, g
from sentry_sdk.integrations.flask import FlaskIntegration
except ImportError:
print("Flask not installed. Run: pip install flask")
return None
# Re-initialize with Flask integration
sentry_sdk.init(
dsn=SENTRY_DSN,
environment=ENVIRONMENT,
release=f"my-app@{RELEASE}",
integrations=[
FlaskIntegration(
transaction_style="url", # or "endpoint"
),
],
traces_sample_rate=0.5,
before_send=before_send_handler,
)
app = Flask(__name__)
@app.before_request
def before_request():
"""Set up request context."""
g.request_id = request.headers.get("X-Request-ID", "unknown")
sentry_sdk.set_tag("request_id", g.request_id)
# Set user context if authenticated
user_id = request.headers.get("X-User-ID")
if user_id:
set_user_context(user_id=user_id)
@app.route("/")
def index():
add_breadcrumb("User visited homepage", category="navigation")
return {"status": "ok", "message": "Welcome to the API"}
@app.route("/api/users/<user_id>")
def get_user(user_id):
add_breadcrumb(f"Fetching user {user_id}", category="api", data={"user_id": user_id})
# Simulate user lookup
if user_id == "0":
raise ValueError("Invalid user ID")
return {"user_id": user_id, "name": "Test User"}
@app.route("/api/error")
def trigger_error():
"""Endpoint to test error tracking."""
division_by_zero = 1 / 0
return {"result": division_by_zero}
@app.route("/api/message")
def send_message():
"""Endpoint to test message capture."""
capture_message(
"User triggered test message",
level="info",
endpoint="/api/message",
custom_data={"test": True}
)
return {"status": "message sent"}
@app.errorhandler(Exception)
def handle_exception(e):
"""Global exception handler."""
# Sentry captures this automatically with FlaskIntegration
# but we can add extra context
sentry_sdk.set_context("error_details", {
"error_type": type(e).__name__,
"error_message": str(e),
"endpoint": request.endpoint,
})
return {"error": str(e)}, 500
return app
# =============================================================================
# ASYNC SUPPORT (Python 3.7+)
# =============================================================================
async def async_capture_example():
"""
Example of capturing errors in async code.
"""
import asyncio
async def async_task_that_fails():
await asyncio.sleep(0.1)
raise RuntimeError("Async task failed")
try:
await async_task_that_fails()
except Exception as e:
capture_exception(e, task="async_example", async_context=True)
# =============================================================================
# MAIN EXAMPLE
# =============================================================================
def main():
"""
Demonstration of all Sentry integration features.
"""
print("=" * 60)
print("Bugsink/Sentry Python SDK Integration Example")
print("=" * 60)
# Initialize Sentry
init_sentry()
# Set user context
set_user_context(
user_id="user-123",
email="developer@example.com",
username="developer",
subscription_tier="premium"
)
# Add breadcrumbs to track user journey
add_breadcrumb("Application started", category="app", level="info")
add_breadcrumb("User authenticated", category="auth", level="info")
add_breadcrumb("Loading dashboard", category="navigation", level="info")
# Example 1: Capture a handled exception
print("\n1. Capturing handled exception...")
try:
result = 10 / 0
except ZeroDivisionError as e:
capture_exception(
e,
operation="division_example",
numerator=10,
denominator=0
)
print(" Exception captured and sent to Bugsink")
# Example 2: Capture a message
print("\n2. Capturing info message...")
capture_message(
"User completed onboarding flow",
level="info",
steps_completed=5,
time_taken_seconds=120
)
print(" Message captured and sent to Bugsink")
# Example 3: Use decorator for automatic tracking
print("\n3. Using @track_errors decorator...")
@track_errors("data_processing")
def process_data(data):
if not data:
raise ValueError("Data cannot be empty")
return len(data)
try:
process_data([])
except ValueError:
print(" Error tracked automatically via decorator")
# Example 4: Transaction for performance monitoring
print("\n4. Creating performance transaction...")
@transaction("batch_operation", op="task")
def batch_operation():
import time
time.sleep(0.1) # Simulate work
return "completed"
batch_operation()
print(" Transaction recorded")
# Example 5: Scoped context
print("\n5. Using scoped context...")
with sentry_sdk.push_scope() as scope:
scope.set_tag("feature", "new_checkout")
scope.set_extra("cart_items", 3)
scope.set_extra("total_amount", 99.99)
capture_message("Checkout initiated", level="info")
print(" Scoped message captured")
# Example 6: Manual transaction with spans
print("\n6. Creating transaction with spans...")
with sentry_sdk.start_transaction(name="order_processing", op="task") as txn:
with txn.start_child(op="db.query", description="Fetch order"):
import time
time.sleep(0.05)
with txn.start_child(op="http.client", description="Payment API"):
time.sleep(0.1)
with txn.start_child(op="db.query", description="Update order status"):
time.sleep(0.05)
txn.set_status("ok")
print(" Transaction with spans recorded")
# Clean up
clear_user_context()
print("\n" + "=" * 60)
print("All examples completed!")
print(f"Check your Bugsink dashboard at: https://{SENTRY_DSN.split('@')[1].split('/')[0]}")
print("=" * 60)
# Flush events before exit
sentry_sdk.flush(timeout=5.0)
if __name__ == "__main__":
main()