Legacy Python client for Sentry error monitoring service with framework integration and exception tracking capabilities.
—
The Client class is the primary interface for capturing and sending events to Sentry. It manages configuration, event processing, context, and communication with Sentry servers.
Initialize a Sentry client with DSN and configuration options.
class Client:
def __init__(self, dsn=None, raise_send_errors=False, transport=None,
install_sys_hook=True, install_logging_hook=True,
hook_libraries=None, enable_breadcrumbs=True,
processors=None, _random_seed=None, **options):
"""
Initialize Sentry client.
Parameters:
- dsn (str): Sentry Data Source Name URL
- raise_send_errors (bool): Raise errors on send failures
- transport (Transport): Custom transport implementation
- install_sys_hook (bool): Install sys.excepthook handler
- install_logging_hook (bool): Install logging breadcrumb hook
- hook_libraries (list): Libraries to hook for breadcrumbs
- enable_breadcrumbs (bool): Enable breadcrumb collection
- processors (list): Data processing pipeline
"""Capture and report exceptions with full stack traces and context.
def captureException(self, exc_info=None, **kwargs):
"""
Capture exception and send to Sentry.
Parameters:
- exc_info (tuple): Exception info tuple (type, value, traceback)
- data (dict): Additional event data
- extra (dict): Extra context data
- fingerprint (list): Custom fingerprint for grouping
- level (str): Event level ('error', 'warning', 'info', etc.)
- logger (str): Logger name
- tags (dict): Event tags
Returns:
str: Event ID
"""Capture custom messages and log entries.
def captureMessage(self, message, **kwargs):
"""
Capture message event.
Parameters:
- message (str): Message text
- level (str): Log level ('debug', 'info', 'warning', 'error', 'fatal')
- data (dict): Additional event data
- extra (dict): Extra context data
- params (tuple): Message formatting parameters
- stack (bool): Include stack trace
Returns:
str: Event ID
"""Capture SQL queries and database operations for performance monitoring.
def captureQuery(self, query, params=(), engine=None, **kwargs):
"""
Capture SQL query event.
Parameters:
- query (str): SQL query string
- params (tuple): Query parameters
- engine (str): Database engine name
- time_spent (float): Query execution time
Returns:
str: Event ID
"""Capture custom event types with arbitrary data.
def capture(self, event_type, **kwargs):
"""
Capture generic event.
Parameters:
- event_type (str): Event type identifier
- message (str): Event message
- data (dict): Event-specific data
- extra (dict): Extra context data
- fingerprint (list): Custom fingerprint
Returns:
str: Event ID
"""Set context information that will be included with all events.
def user_context(self, data):
"""
Set user context information.
Parameters:
- data (dict): User data with keys like 'id', 'username', 'email', 'ip_address'
"""
def tags_context(self, data):
"""
Set tags for event categorization and filtering.
Parameters:
- data (dict): Tag key-value pairs
"""
def extra_context(self, data):
"""
Set extra context data for debugging.
Parameters:
- data (dict): Additional context information
"""
def http_context(self, data):
"""
Set HTTP request context.
Parameters:
- data (dict): HTTP context with 'url', 'method', 'headers', etc.
"""Record breadcrumbs for tracking user actions and application state.
def captureBreadcrumb(self, message=None, timestamp=None, level=None,
category=None, data=None, type=None, processor=None):
"""
Record breadcrumb for context tracking.
Parameters:
- message (str): Breadcrumb message
- timestamp (datetime): Breadcrumb timestamp
- level (str): Breadcrumb level
- category (str): Breadcrumb category
- data (dict): Additional breadcrumb data
- type (str): Breadcrumb type
- processor (callable): Custom breadcrumb processor
"""Build event data structures and send to Sentry.
def build_msg(self, event_type, data=None, date=None, time_spent=None,
extra=None, stack=None, tags=None, fingerprint=None, **kwargs):
"""
Build event data structure.
Parameters:
- event_type (str): Type of event
- data (dict): Event-specific data
- date (datetime): Event timestamp
- time_spent (float): Time spent processing
- extra (dict): Extra context
- stack (bool): Include stack trace
- tags (dict): Event tags
- fingerprint (list): Custom fingerprint
Returns:
dict: Event data structure
"""
def send(self, **data):
"""
Send event data to Sentry.
Parameters:
- **data: Event data dictionary
Returns:
str: Event ID
"""Automatic exception capture using context manager or decorator.
def capture_exceptions(self, function_or_exceptions=None, **kwargs):
"""
Wrap function or code block to automatically capture exceptions.
Can be used as a decorator or context manager.
Parameters:
- function_or_exceptions (callable|tuple): Function to wrap or exception types to catch
- **kwargs: Additional parameters passed to captureException
Returns:
callable|contextmanager: Decorator or context manager
"""Check client status and get version information.
def is_enabled(self):
"""
Check if client should attempt to send events.
Returns:
bool: True if client is enabled and can send events
"""
def should_capture(self, exc_info):
"""
Determine if exception should be captured based on ignore rules.
Parameters:
- exc_info (tuple): Exception info tuple (type, value, traceback)
Returns:
bool: True if exception should be captured
"""
def get_module_versions(self):
"""
Get version information for included modules.
Returns:
dict: Module name to version mapping
"""Access client configuration and utility methods.
def get_public_dsn(self, scheme=None):
"""
Get public DSN for client-side usage.
Parameters:
- scheme (str): URL scheme override
Returns:
str: Public DSN URL
"""
@property
def context(self):
"""
Get thread-local context manager.
Returns:
Context: Context instance for current thread
"""
@property
def last_event_id(self):
"""
Get ID of last captured event.
Returns:
str: Last event ID
"""from raven import Client
client = Client('https://your-dsn@sentry.io/project-id')
try:
result = risky_operation()
except Exception as e:
event_id = client.captureException()
print(f"Error captured with ID: {event_id}")# Log different severity levels
client.captureMessage('User login successful', level='info')
client.captureMessage('Database connection slow', level='warning')
client.captureMessage('Critical system failure', level='error')# Set user context
client.user_context({
'id': 123,
'username': 'john_doe',
'email': 'john@example.com'
})
# Set custom tags
client.tags_context({
'environment': 'production',
'version': '1.2.3',
'feature_flag': 'new_checkout'
})
# Add extra debugging info
client.extra_context({
'request_id': 'req_abc123',
'user_agent': 'Mozilla/5.0...',
'session_duration': 1847
})# Record user actions
client.captureBreadcrumb(
message='User clicked checkout button',
category='ui.click',
level='info',
data={'button_id': 'checkout-btn'}
)
client.captureBreadcrumb(
message='Payment processing started',
category='payment',
level='info',
data={'amount': 99.99, 'currency': 'USD'}
)
# When an error occurs, breadcrumbs provide context
try:
process_payment()
except PaymentError:
client.captureException() # Includes breadcrumb history# As a decorator
@client.capture_exceptions
def risky_function():
return 1 / 0 # Exception automatically captured
# As a context manager
with client.capture_exceptions():
risky_operation() # Any exception is captured and re-raised
# Specify specific exceptions to capture
@client.capture_exceptions((IOError, ValueError))
def file_operation():
with open('nonexistent.txt') as f:
return f.read()
# With additional context
with client.capture_exceptions(extra={'operation': 'file_upload'}):
upload_file()# Check if client is enabled before expensive operations
if client.is_enabled():
try:
expensive_operation()
except Exception:
client.captureException()
# Check if specific exception should be captured
try:
risky_operation()
except Exception as e:
exc_info = sys.exc_info()
if client.should_capture(exc_info):
client.captureException(exc_info)
# Get module version information
versions = client.get_module_versions()
print(f"Python version: {versions.get('python')}")
print(f"Django version: {versions.get('django', 'Not installed')}")Install with Tessl CLI
npx tessl i tessl/pypi-raven