Legacy Python client for Sentry error monitoring service with framework integration and exception tracking capabilities.
—
Raven provides comprehensive integrations with popular Python web frameworks, offering automatic error capture, request context, and framework-specific features.
Enhanced Sentry client with Django-specific features and automatic integration.
from raven.contrib.django.client import DjangoClient
class DjangoClient(Client):
def __init__(self, **kwargs):
"""
Django-enhanced Sentry client.
Automatically reads configuration from Django settings.
"""
def get_client(client=None, reset=False):
"""
Get configured Django Sentry client.
Parameters:
- client (str): Client class path override
- reset (bool): Reset cached client instance
Returns:
DjangoClient: Configured client instance
"""
def sentry_exception_handler(sender, **kwargs):
"""
Django signal handler for exception capture.
Parameters:
- sender: Signal sender
- **kwargs: Signal arguments including request
"""from raven.contrib.django.middleware import SentryMiddleware, Sentry404CatchMiddleware, SentryResponseErrorIdMiddleware
class SentryMiddleware:
"""General Sentry middleware for Django requests."""
def process_exception(self, request, exception): ...
class Sentry404CatchMiddleware:
"""Middleware to capture 404 errors."""
def process_response(self, request, response): ...
class SentryResponseErrorIdMiddleware:
"""Middleware to add Sentry error ID to responses."""
def process_response(self, request, response): ...from raven.contrib.django.handlers import SentryHandler
class SentryHandler(logging.Handler):
"""Django-specific Sentry logging handler."""
def __init__(self, **kwargs):
"""
Initialize handler with Django settings integration.
"""Seamless Flask application integration with automatic error capture and request context.
from raven.contrib.flask import Sentry
class Sentry:
def __init__(self, app=None, client=None, client_cls=None, dsn=None,
logging=None, level=logging.ERROR, logging_exclusions=None,
wrap_wsgi=None, register_signal=True, **kwargs):
"""
Flask Sentry integration.
Parameters:
- app (Flask): Flask application instance
- client (Client): Custom client instance
- client_cls (type): Custom client class
- dsn (str): Sentry DSN override
- logging (bool): Enable logging integration
- level (int): Minimum logging level
- logging_exclusions (tuple): Excluded logger names
- wrap_wsgi (bool): Wrap WSGI application
- register_signal (bool): Register Flask error signal
"""
def init_app(self, app, dsn=None, **kwargs):
"""
Initialize Sentry for Flask app.
Parameters:
- app (Flask): Flask application
- dsn (str): Sentry DSN
- **kwargs: Additional configuration
"""
def captureException(self, exc_info=None, **kwargs):
"""Capture exception with Flask request context."""
def captureMessage(self, message, **kwargs):
"""Capture message with Flask request context."""from raven.contrib.bottle import Sentry
class Sentry:
def __init__(self, app, client=None, **kwargs):
"""
Bottle Sentry integration.
Parameters:
- app: Bottle application instance
- client (Client): Custom client instance
"""Automatic error capture for Celery task execution.
from raven.contrib.celery import SentryCeleryHandler, register_signal, register_logger_signal
def register_signal(client, ignore_expected=False):
"""
Register Celery signal handler for task failures.
Parameters:
- client (Client): Sentry client instance
- ignore_expected (bool): Ignore expected task failures
"""
def register_logger_signal(client, logger=None, loglevel=logging.ERROR):
"""
Register Celery logger signal handler.
Parameters:
- client (Client): Sentry client instance
- logger (str): Logger name
- loglevel (int): Minimum log level
"""
class SentryCeleryHandler:
def __init__(self, client):
"""
Celery task failure handler.
Parameters:
- client (Client): Sentry client instance
"""Asynchronous Sentry client for Tornado applications.
from raven.contrib.tornado import AsyncSentryClient
class AsyncSentryClient(Client):
def __init__(self, **kwargs):
"""
Tornado async Sentry client.
Uses Tornado's async HTTP client for non-blocking sends.
"""
def send(self, **data):
"""
Send event asynchronously.
Returns:
tornado.concurrent.Future: Async send operation
"""from raven.contrib.pylons import Sentry
class Sentry:
def __init__(self, config, client_cls=None):
"""
Pylons Sentry integration.
Parameters:
- config (dict): Pylons configuration
- client_cls (type): Custom client class
"""Specialized client for serverless AWS Lambda functions.
from raven.contrib.awslambda import LambdaClient
class LambdaClient(Client):
def __init__(self, **kwargs):
"""
AWS Lambda optimized Sentry client.
Handles Lambda-specific context and constraints.
"""Modern async web framework integration.
from raven.contrib.sanic import Sentry
class Sentry:
def __init__(self, app=None, **kwargs):
"""
Sanic Sentry integration.
Parameters:
- app: Sanic application instance
"""Integration for the web.py web framework.
from raven.contrib.webpy import SentryApplication
class SentryApplication(web.application):
def __init__(self, client, mapping=None, fvars=None, logging=False,
level=logging.ERROR, **kwargs):
"""
Web.py application with Sentry integration.
Parameters:
- client (Client): Sentry client instance
- mapping: URL mapping
- fvars: Global variables
- logging (bool): Enable automatic logging integration
- level (int): Minimum logging level
"""WSGI middleware integration for Paste framework.
from raven.contrib.paste import sentry_filter_factory
def sentry_filter_factory(app, global_conf, **kwargs):
"""
Factory function for Paste/WSGI integration.
Parameters:
- app: WSGI application
- global_conf (dict): Global configuration
- **kwargs: Client configuration options
Returns:
callable: WSGI middleware
"""Middleware for ZeroRPC distributed computing framework.
from raven.contrib.zerorpc import SentryMiddleware
class SentryMiddleware:
def __init__(self, hide_zerorpc_frames=True, client=None, **kwargs):
"""
ZeroRPC middleware for automatic exception capture.
Parameters:
- hide_zerorpc_frames (bool): Hide ZeroRPC internal frames from stack traces
- client (Client): Existing Sentry client instance
- **kwargs: Client configuration options
"""Integration for Zope web application framework.
from raven.contrib.zope import ZopeSentryHandler
class ZopeSentryHandler:
def __init__(self, dsn=None, **kwargs):
"""
Zope exception handler for Sentry integration.
Parameters:
- dsn (str): Sentry DSN
- **kwargs: Client configuration options
"""Configuration integration for ZConfig-based applications.
from raven.contrib.zconfig import logger_factory
def logger_factory():
"""
ZConfig logger factory for Sentry integration.
"""# settings.py
INSTALLED_APPS = [
'raven.contrib.django',
# ... other apps
]
RAVEN_CONFIG = {
'dsn': 'https://your-dsn@sentry.io/project-id',
'release': '1.0.0',
'environment': 'production',
}
MIDDLEWARE = [
'raven.contrib.django.middleware.SentryMiddleware',
# ... other middleware
]
LOGGING = {
'version': 1,
'handlers': {
'sentry': {
'level': 'ERROR',
'class': 'raven.contrib.django.handlers.SentryHandler',
},
},
'loggers': {
'root': {
'handlers': ['sentry'],
},
}
}
# Usage in views
from raven.contrib.django.models import client
def my_view(request):
try:
risky_operation()
except Exception:
client.captureException()
return HttpResponse('Error occurred')from flask import Flask
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config['SENTRY_DSN'] = 'https://your-dsn@sentry.io/project-id'
sentry = Sentry(app)
@app.route('/error')
def error():
try:
1/0
except ZeroDivisionError:
sentry.captureException()
return 'Error captured!'
@app.route('/message')
def message():
sentry.captureMessage('User accessed message endpoint')
return 'Message sent to Sentry'from celery import Celery
from raven.contrib.celery import register_signal, register_logger_signal
from raven import Client
client = Client('https://your-dsn@sentry.io/project-id')
# Register signal handlers
register_signal(client)
register_logger_signal(client)
app = Celery('myapp')
@app.task
def risky_task():
# Any exception will be automatically captured
return 1/0import tornado.web
from raven.contrib.tornado import AsyncSentryClient
class MainHandler(tornado.web.RequestHandler):
def initialize(self):
self.sentry = AsyncSentryClient('https://your-dsn@sentry.io/project-id')
async def get(self):
try:
await some_async_operation()
except Exception:
await self.sentry.captureException()
self.write('Error occurred')import web
from raven import Client
from raven.contrib.webpy import SentryApplication
urls = (
'/', 'index',
'/error', 'error'
)
client = Client('https://your-dsn@sentry.io/project-id')
class index:
def GET(self):
return "Hello, World!"
class error:
def GET(self):
raise Exception("Test error")
# Create application with Sentry integration
app = SentryApplication(client, mapping=urls, fvars=globals(), logging=True)
if __name__ == "__main__":
app.run()import zerorpc
from raven.contrib.zerorpc import SentryMiddleware
# Set up Sentry middleware
sentry = SentryMiddleware(dsn='https://your-dsn@sentry.io/project-id')
zerorpc.Context.get_instance().register_middleware(sentry)
class HelloRPC:
def hello(self):
return "Hello World"
def error(self):
# This exception will be automatically captured
raise Exception("RPC error occurred")
s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()# In your Paste configuration file (development.ini, production.ini, etc.)
[filter:sentry]
use = egg:raven#sentry
dsn = https://your-dsn@sentry.io/project-id
include_paths = myapp
level = WARN
[pipeline:main]
pipeline = sentry myapp
[app:myapp]
use = egg:MyAppInstall with Tessl CLI
npx tessl i tessl/pypi-raven