Rollbar Python SDK (pyrollbar)

repository·master·Indexed 42 days ago

https://github.com/rollbar/pyrollbar

A Python notifier for real-time exception tracking and error monitoring. Pyrollbar supports Python 3.10 through 3.14 (v1.5.0) and provides official integrations for Django, Flask, FastAPI, Celery, Pyramid, and AWS Lambda. It features asynchronous reporting via httpx, local variable capture in tracebacks, and a CLI for reporting messages. Key functions include rollbar.init() for configuration, report_exc_info() for exceptions, and report_message() for arbitrary log messages.

Tokens
6.5K
Snippets
21
Records
28
Agent score
53%

What's inside Rollbar

  1. Install and configure Pyrollbar

    master

    To start reporting exceptions, errors, and log messages to Rollbar, follow these steps:

    1. Sign up: Create an account at Rollbar.
    2. Install and Configure: Follow the official Python SDK Quick Start guide to install the rollbar package and set up your configuration for your specific platform.

    Pyrollbar is compatible with most Python frameworks, with official integrations available for Django, Flask, FastAPI, Celery, Pyramid, and AWS Lambda.

  2. Capture local variables in tracebacks

    master

    Pyrollbar can capture the values of local variables at each frame of a traceback to provide deeper debugging context.

    This is controlled by the locals setting in your configuration. To capture locals, the frame must either be the last frame in the traceback or belong to a file within the directory specified by the root setting.

    Note that variables are serialized and transformed (scrubbed/redacted) before being sent to ensure sensitive data is protected.

  3. How Pyrollbar extracts request and person data

    master

    Pyrollbar automatically enriches error reports with context from web requests.

    Request Data: When a request object is passed to report_exc_info or report_message, Pyrollbar detects the framework (e.g., Django, Flask/Werkzeug, Starlette, FastAPI, Tornado, Bottle, Sanic, Falcon) and extracts:

    • URL, Method, and Headers
    • GET and POST parameters
    • User IP (respecting X-Forwarded-For or X-Real-Ip if configured)
    • Request body (if include_request_body is enabled in settings)

    Person Data: Pyrollbar attempts to identify the logged-in user by looking for:

    1. A rollbar_person attribute on the request.
    2. A user attribute (common in Starlette/FastAPI).
    3. A user_id attribute.

    If capture_username or capture_email are set to False in your configuration, these fields will be scrubbed from the payload.

  4. Configure async handlers for Rollbar

    master

    To use asynchronous reporting functions (report_exc_info or report_message), you must ensure your Rollbar configuration uses an async-compatible handler.

    Supported handlers for async operations include:

    • async
    • httpx

    If you attempt to use try_report with a handler that is not in the allowed list (and is not the default handler), a RollbarAsyncError will be raised. Additionally, httpx must be installed in your environment for async reporting to function.

  5. Handle paginated results from search_items()

    master

    When search_items() returns a PagedResult, you can navigate through pages of results using .next_page() and .prev_page().

    Example:

    result = rollbar.search_items(title='foo')
    print(f"First page: {result.data}")
    
    # Get the next page
    next_page_result = result.next_page()
    print(f"Second page: {next_page_result.data}")
    result = rollbar.search_items(title='foo', fields=['id'])
    print(f'First page: {result.page}, data: {result.data}')
    result = result.next_page()
    print(f'Second page: {result.page}, data: {result.data}')
  6. Configure RollbarHandler levels and history

    master

    The RollbarHandler distinguishes between two types of levels:

    1. Notification Level: The level at which log records are actually sent to Rollbar. Use setLevel(level) to control this.
    2. History Level: The level at which log records are stored in local memory to provide context for future reports. Use setHistoryLevel(level) to control this.

    When an error is reported, the handler can include a recent history of logs (up to history_size) in the Rollbar payload, providing valuable context leading up to the error.

    from rollbar.logger import RollbarHandler
    import logging
    
    # history_size: how many previous records to keep in memory
    # history_level: which records to keep in history (e.g., DEBUG)
    # level: which records to actually report to Rollbar (e.g., ERROR)
    handler = RollbarHandler(
        history_size=10,
        history_level=logging.DEBUG,
        level=logging.ERROR
    )
    
    # You can also adjust these after instantiation
    handler.setHistoryLevel(logging.INFO)
    handler.setLevel(logging.CRITICAL)
  7. Initialize Pyrollbar with init()

    master

    Use rollbar.init() to configure your project access token and environment. This function sets up the global SETTINGS and configures the transport mechanism for reporting errors.

    Key configuration options include:

    • access_token: (Required) Your project access token.
    • environment: The environment name (e.g., 'production').
    • scrub_fields: A list of sensitive field names to redact (values replaced with *).
    • url_fields: A list of field names treated as URLs to be parsed and scrubbed.
    • handler: The reporting method. Options include 'default', 'blocking', 'thread', 'async', 'agent', 'tornado', 'gae', 'twisted', 'httpx', or 'thread_pool'.
    • capture_ip: Set to True to capture client IP, 'anonymize' to mask it, or False to skip.
    import rollbar
    
    rollbar.init(
        access_token='YOUR_PROJECT_ACCESS_TOKEN',
        environment='production',
        scrub_fields=['password', 'secret'],
        handler='thread'
    )
  8. Use the Rollbar CLI to report messages

    master

    The Rollbar CLI allows you to send log messages or errors directly to your Rollbar project from the command line. You can use it by providing a command (the severity level) followed by the message text. The CLI supports both direct arguments and reading from standard input (stdin).

    Severity Commands

    Use one of the following commands to specify the level of the message:

    • debug
    • info
    • warning
    • error
    • critical

    Usage Patterns

    Direct Argument Mode: Pass the command and the message as arguments:

    rollbar error "Something went wrong"

    Interactive/Stdin Mode: You can pipe input into the CLI or use it interactively. When reading from stdin, the first word of a line is treated as the command, and the rest is the message:

    echo "info system_started" | rollbar
    rollbar error "Your message here"
  9. Integrate Rollbar with Python logging using RollbarHandler

    master

    You can integrate Rollbar into your application's existing Python logging setup by using the RollbarHandler. This handler captures log records and reports them to Rollbar.

    To use it, initialize Rollbar first, then instantiate the handler and add it to your logger (or the root logger to capture all logs).

    import logging
    import rollbar
    from rollbar.logger import RollbarHandler
    
    # Initialize Rollbar
    rollbar.init('ACCESS_TOKEN', 'ENVIRONMENT')
    
    # Setup your logger
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    
    # Create the RollbarHandler
    # By default, it reports ERROR and above to Rollbar
    rollbar_handler = RollbarHandler()
    rollbar_handler.setLevel(logging.ERROR)
    
    # Attach the handler to your logger
    logger.addHandler(rollbar_handler)
    
    # Now, logging an error will report to Rollbar
    logger.error("Something went wrong!")
  10. Configure reporting handlers

    master

    The handler setting determines how payloads are sent to the Rollbar API.

    Available handlers:

    • 'default': Uses a single-use thread (default).
    • 'blocking': Makes the HTTP request immediately and blocks execution.
    • 'thread': Starts a single-use thread and returns immediately.
    • 'async': Uses an async HTTP request (requires Python 3.4+).
    • 'agent': Writes to a log file (must end in .rollbar) to be processed by rollbar-agent.
    • 'tornado': Uses Tornado's AsyncHTTPClient.
    • 'gae': Uses Google App Engine's urlfetch.
    • 'twisted': Uses Twisted and treq.
    • 'httpx': Uses httpx for async requests (requires Python 3.7+).
    • 'thread_pool': Uses a pool of worker threads (requires Python 3.2+).
  11. Python and Framework compatibility

    master

    Pyrollbar supports various Python versions and web frameworks.

    Python Version Support

    • v1.5.0 (Current): Full support for Python 3.10, 3.11, 3.12, 3.13, and 3.14.
    • v0.16.3: Security fixes only for Python 2.7 and 3.4 through 3.11.

    Framework Support

    Official support includes maintained integrations and CI testing for:

    • Django: Versions 4.2, 5.2 (Supported for Release/LTS end + 1 year).
    • FastAPI: Versions 0.115, 0.118 (Supported for Release + 1 year).
    • Flask: Versions 2.3, 3.1 (Supported for Release + 1 year).
    • Pyramid: Versions 1.10, 2.0 (Supported for Release + 1 year).
    • Celery: (Supported for Release + 1 year).

    Other frameworks like AWS Lambda are supported, and additional community-supported integrations are available.

  12. Manage user session context with session management APIs

    master

    Pyrollbar provides utilities to track and propagate user context (session data) across requests using 'baggage' headers. This allows you to maintain a consistent session_id and execution_scope_id throughout a distributed request flow.

    Key functions:

    • set_current_session(headers): Parses session data from a dictionary of request headers and stores it in the current context (supporting both async ContextVar and thread-local storage).
    • get_current_session(): Retrieves the current list of session attributes. Do NOT modify the returned list directly.
    • reset_current_session(): Clears the current session data.
    • get_propagation_header(): Generates a string formatted for the baggage HTTP header, which can be used to propagate the current session_id and execution_scope_id to outgoing requests.
    from rollbar.lib.session import set_current_session, get_current_session, get_propagation_header
    
    # Example: Setting session from incoming request headers
    incoming_headers = {'baggage': 'rollbar.session.id=12345,rollbar.execution.scope.id=abcde'}
    set_current_session(incoming_headers)
    
    # Example: Getting session data
    session = get_current_session()
    print(session)
    
    # Example: Preparing header for an outgoing request
    propagation_header = get_propagation_header()
    # propagation_header will be: 'rollbar.session.id=12345,rollbar.execution.scope.id=abcde'
    print(f"Baggage: {propagation_header}")