### Interactive Usage Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Shows how to start the Rollbar CLI in interactive mode and send multiple messages. ```bash # Start in interactive mode rollbar -t YOUR_TOKEN -e production # Type commands (press Enter after each): > error Database error occurred > warning Memory usage high > info User logged in > critical System shutdown initiated > debug Debug information # Press Ctrl+C to exit ``` -------------------------------- ### Basic RollbarHandler Setup with init() Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/logging-handler.md Initializes Rollbar and the RollbarHandler in a single step for basic logging integration. This setup sends logs at ERROR level and above to Rollbar. ```python import logging from rollbar.logger import RollbarHandler # Initialize Rollbar and handler in one call handler = RollbarHandler('YOUR_ACCESS_TOKEN', 'production') handler.setLevel(logging.ERROR) logger = logging.getLogger(__name__) logger.addHandler(handler) # Now logs at ERROR and CRITICAL go to Rollbar logger.error('Something went wrong') logger.info('This is not reported (below ERROR level)') ``` -------------------------------- ### Interactive Mode Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Demonstrates how to start the Rollbar CLI in interactive mode to accept messages from stdin. ```bash rollbar -t YOUR_ACCESS_TOKEN -e production # Then type: error This is an error # And: warning This is a warning # Press Ctrl+C to exit ``` -------------------------------- ### Example Attributes List Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/types-and-payloads.md Illustrates how to format a list of attributes for Rollbar payloads. ```python attributes = [ {'key': 'execution_scope_id', 'value': 'a1b2c3d4e5f6789...'}, {'key': 'session_id', 'value': 'sess_12345'} ] ``` -------------------------------- ### One-Shot Command Examples Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Examples of reporting a single message with different log levels and environments using the Rollbar CLI. ```bash rollbar -t YOUR_ACCESS_TOKEN -e production error "An error occurred" rollbar -t YOUR_ACCESS_TOKEN -e staging warning "Something to watch" rollbar -t YOUR_ACCESS_TOKEN -e dev info "Info message" ``` -------------------------------- ### Verbose Output Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Demonstrates how to enable verbose output for the Rollbar CLI to see messages before they are sent. ```bash rollbar -t TOKEN -e production -v info "This message will be printed" # Output: Rollbar [info]: This message will be printed ``` -------------------------------- ### ShortenerTransform Example Usage Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Example of initializing ShortenerTransform to truncate specific fields and limit list items and string lengths. ```python from rollbar.lib.transforms.shortener import ShortenerTransform shortener = ShortenerTransform( keys=[('body', 'trace', 'frames', '*', 'locals', '*')], maxstring=200, maxlist=5 ) # Truncates local variable values in exception frames ``` -------------------------------- ### Install Pyrollbar CLI Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Command to install the pyrollbar package using pip. ```bash pip install rollbar ``` -------------------------------- ### Cron Job Example for Monitoring and Reporting Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md An example of a cron job that monitors a backup script and reports success or failure to Rollbar. ```bash # Monitor a cron job and report errors 0 2 * * * /usr/local/bin/backup.sh 2>&1 | tee /tmp/backup.log && \ rollbar -t TOKEN -e production info "Daily backup completed" || \ (tail -20 /tmp/backup.log | rollbar -t TOKEN -e production critical "Daily backup failed") ``` -------------------------------- ### RollbarHandler Emit Method Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/logging-handler.md Demonstrates how to set up and use the RollbarHandler for reporting exceptions and messages to Rollbar, including custom extra data. This example shows exception reporting, message reporting with extra data, and custom extra data inclusion. ```python import logging import rollbar # Setup logger = logging.getLogger(__name__) handler = rollbar.logger.RollbarHandler('ACCESS_TOKEN', 'production') handler.setLevel(logging.ERROR) logger.addHandler(handler) # Exception reporting try: 1 / 0 except: logger.exception('An error occurred') # Reports to Rollbar with traceback # Message reporting logger.error('Database connection failed', extra={'connection': 'primary'}) # Custom extra data logger.info('User action', extra={ 'extra_data': { 'user_id': 123, 'action': 'login' } }) ``` -------------------------------- ### Event Handler Ordering Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/events-filters.md Illustrates how multiple handlers of the same type are executed in the order they are registered, unless a specific position is provided during registration. ```python events.add_exception_info_handler(handler1) events.add_exception_info_handler(handler2) events.add_exception_info_handler(handler3) ``` -------------------------------- ### Bash Script for Logging to Rollbar Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md A bash script example demonstrating how to create a function to log messages to Rollbar. ```bash #!/bin/bash ROLLBAR_TOKEN="aaaabbbbccccddddeeeeffff00001111" ROLLBAR_ENV="production" log_to_rollbar() { local level=$1 local message=$2 rollbar -t "$ROLLBAR_TOKEN" -e "$ROLLBAR_ENV" "$level" "$message" } # Use in scripts if ! command -v required_tool &> /dev/null; log_to_rollbar error "Required tool not found" exit 1 fi log_to_rollbar info "Backup started" if perform_backup; log_to_rollbar info "Backup completed successfully" else log_to_rollbar critical "Backup failed" fi ``` -------------------------------- ### Initialize Pyrollbar with Environment Variables Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Configure Pyrollbar using environment variables for flexibility in different deployment environments. This example shows how to map common configuration options to environment variables. ```python import os import rollbar rollbar.init( os.getenv('ROLLBAR_ACCESS_TOKEN'), environment=os.getenv('ROLLBAR_ENVIRONMENT', 'production'), root=os.getenv('APP_ROOT', '/app'), branch=os.getenv('GIT_BRANCH'), code_version=os.getenv('APP_VERSION'), enabled=os.getenv('ROLLBAR_ENABLED', 'true').lower() == 'true', handler=os.getenv('ROLLBAR_HANDLER', 'thread'), timeout=int(os.getenv('ROLLBAR_TIMEOUT', '3')) ) ``` -------------------------------- ### Report an Error with Specific Token and Environment Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Example of reporting an error message with a specific access token and environment. ```bash rollbar -t aaaabbbbccccddddeeeeffff00001111 \ -e production \ error "Database connection failed" ``` -------------------------------- ### Configure Scrub Fields and URL Fields Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Example of initializing Rollbar and overriding default sensitive fields and URL fields to be scrubbed. ```python import rollbar rollbar.init( 'TOKEN', 'production', # Override default scrub fields scrub_fields=['password', 'api_key', 'secret_token'], # Override default URL fields to scrub url_fields=['url', 'redirect_uri'] ) ``` -------------------------------- ### Report Info Message with Thread Handler Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Example of sending an info message using the 'thread' handler for non-blocking behavior. ```bash rollbar -t TOKEN -e staging -m thread info "Non-blocking report" ``` -------------------------------- ### Complete Pyrollbar Event Handling Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/events-filters.md Demonstrates registering custom exception and payload handlers to skip timeouts and add server hostnames to reports. Ensure Rollbar is initialized before registering handlers. ```python import rollbar import os from rollbar import events # Initialize rollbar.init('TOKEN', 'production') # Skip timeouts def skip_timeouts(exc_info, **kw): cls, exc, trace = exc_info if 'Timeout' in cls.__name__: return False return exc_info # Add request context def add_request_info(payload, **kw): payload['data']['custom'] = payload['data'].get('custom', {}) payload['data']['custom']['server'] = os.environ.get('HOSTNAME') return payload # Register handlers events.add_exception_info_handler(skip_timeouts) events.add_payload_handler(add_request_info) # Now all reports have server info and skip timeouts rollbar.report_message('App started') try: requests.get('http://slow-api', timeout=1) except Exception: rollbar.report_exc_info() # Skipped if timeout ``` -------------------------------- ### Log History Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/logging-handler.md Demonstrates how prior log messages are included in the 'server.history' section of an ERROR payload when the history mechanism is enabled. ```python logger.debug('Starting operation') logger.info('Processing item 1') logger.info('Processing item 2') logger.error('Item 2 processing failed') # Reports with history of prior 2 messages # In Rollbar payload, under data.server.history: # [ # {'timestamp': ..., 'format': 'Starting operation', ...}, # {'timestamp': ..., 'format': 'Processing item 1', ...}, # {'timestamp': ..., 'format': 'Processing item 2', ...} # ] ``` -------------------------------- ### Customizing Scrub and URL Fields Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Example of initializing pyrollbar with custom lists for sensitive fields to redact and URL fields to scrub query parameters from. ```python rollbar.init( 'TOKEN', 'production', scrub_fields=['password', 'api_key', 'oauth_token', 'credit_card'], url_fields=['url', 'redirect_to', 'return_url'] ) ``` -------------------------------- ### Example Logged Payload on Error Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/error-handling.md An example of a logged payload when `log_payload_on_error` is enabled and an error occurs. It shows the structure of the data that was attempted to be sent to Rollbar. ```text WARNING Payload was: { "access_token": "...", "data": { "level": "error", ... } } ``` -------------------------------- ### ScrubUrlTransform Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Illustrates how `ScrubUrlTransform` removes query parameters from URLs that match configured scrub fields, enhancing data privacy. ```text # Original URL: https://example.com/api?password=secret&token=xyz # After scrub: https://example.com/api ``` -------------------------------- ### Complete Pyrollbar Production Configuration Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md A comprehensive example demonstrating how to configure Pyrollbar for a production environment using various settings and environment variables. Ensure necessary environment variables like ROLLBAR_TOKEN are set. ```python import rollbar import os # Typical production configuration rollbar.init( access_token=os.environ['ROLLBAR_TOKEN'], environment=os.environ.get('ENV', 'production'), root='/app', branch=os.environ.get('GIT_BRANCH', 'main'), code_version=os.environ.get('APP_VERSION'), enabled=True, handler='thread', # Non-blocking timeout=5, verify_https=True, capture_ip='anonymize', capture_email=True, capture_username=False, include_request_body=False, allow_logging_basic_config=False, scrub_fields=[ 'password', 'api_key', 'secret', 'token', 'oauth_token', 'authorization' ], url_fields=['url', 'redirect_uri'], locals={ 'enabled': True, 'safe_repr': True, 'sizes': { 'maxstring': 200, 'maxlist': 20 } }, exception_level_filters=[ ('django.http.Http404', 'ignored'), ], log_all_rate_limited_items=False, suppress_reinit_warning=False ) ``` -------------------------------- ### Report a Warning with a Custom Endpoint Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Example of reporting a warning message using a custom Rollbar API endpoint. ```bash rollbar -t TOKEN \ -e production \ -u https://api-internal.example.com/api/1/ \ warning "Custom endpoint warning" ``` -------------------------------- ### Install and Use Custom Email Masking Transform Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Demonstrates how to initialize Pyrollbar with a custom transform to mask email addresses in payloads. This ensures sensitive email information is protected. ```python import rollbar # Install the custom transform rollbar.init( 'TOKEN', 'production', custom_transforms=[MaskEmailTransform()] ) # Now all emails in payloads are masked rollbar.report_message('User signup', extra_data={ 'email': 'alice@example.com' # Will be masked to a*****e@example.com }) ``` -------------------------------- ### Configuring Request Pool Settings Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Example of initializing pyrollbar with custom settings for its request connection pooling. This allows tuning the number of connection pools, maximum connections per pool, and maximum retries per request. ```python rollbar.init( 'TOKEN', 'production', request_pool_connections=1, request_pool_maxsize=5, request_max_retries=3 ) ``` -------------------------------- ### Pipe Output from Another Command Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Example of piping the output of another command (like 'echo') to the Rollbar CLI for reporting. ```bash # Report the output of another command echo "An error occurred" | rollbar -t TOKEN -e production error # Report from a script cat error.log | while read line; rollbar -t TOKEN -e production warning "$line" done ``` -------------------------------- ### W3C Baggage Header Examples Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Demonstrates various valid formats for the W3C Baggage header, including cases with both session and scope IDs, only session ID, and with extraneous properties. ```text # With both properties baggage: rollbar.session.id=sess_123, rollbar.execution.scope.id=scope_456 # Only session ID baggage: rollbar.session.id=sess_789 # With other properties (ignored) baggage: user-id=alice, rollbar.execution.scope.id=scope_xyz, service-name=web # Case-insensitive header name Baggage: rollbar.execution.scope.id=scope_000 # Multiple spaces (handled) baggage: rollbar.session.id=sess_111 , rollbar.execution.scope.id=scope_222 ``` -------------------------------- ### Install Rollbar ReporterMiddleware for Starlette Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Add the ReporterMiddleware to your Starlette application to catch exceptions and report them to Rollbar. Ensure Rollbar is initialized before adding the middleware. ```python from starlette.applications import Starlette from rollbar.contrib.starlette import ReporterMiddleware import rollbar app = Starlette() rollbar.init('YOUR_ACCESS_TOKEN', 'production') app.add_middleware(ReporterMiddleware) ``` -------------------------------- ### Report Error with Blocking Handler Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Example of sending an error message using the 'blocking' handler to wait for completion. ```bash rollbar -t TOKEN -e production -m blocking error "Wait for completion" ``` -------------------------------- ### Custom Transform Example: LogSensitiveDataTransform Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Defines a custom transform that logs a warning when a 'password' field is detected. It runs before default scrubbing. ```python import rollbar from rollbar.lib.transform import Transform class LogSensitiveDataTransform(Transform): priority = 5 # Run before scrubbing def transform_dict(self, o, key=None): if key and 'password' in key: import logging logging.warning(f'Found password field at {key}') return o rollbar.init( 'TOKEN', 'production', custom_transforms=[LogSensitiveDataTransform()] ) ``` -------------------------------- ### RollbarHandler Setup with Separate Rollbar Init Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/logging-handler.md Configures the RollbarHandler after initializing Rollbar separately. This approach allows for more granular control over Rollbar's initialization parameters before creating the handler. ```python import logging import rollbar from rollbar.logger import RollbarHandler # Initialize Rollbar separately rollbar.init('YOUR_ACCESS_TOKEN', 'production') # Create handler without init handler = RollbarHandler() handler.setLevel(logging.WARNING) logger = logging.getLogger(__name__) logger.addHandler(handler) logger.warning('Watch out!') # Reports to Rollbar ``` -------------------------------- ### Grafana Alert Webhook Configuration Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Example JSON configuration for a Grafana webhook to send alerts to Rollbar via the CLI. ```json { "url": "http://your-server/webhook", "body": "alert | xargs -I {} rollbar -t TOKEN -e production critical '{}'" } ``` -------------------------------- ### Exception Payload Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/types-and-payloads.md This is a typical payload structure for reporting an exception. It includes environment details, traceback information, request context, and person data. ```json { "access_token": "aaaabbbbccccddddeeeeffff00001111", "data": { "environment": "production", "level": "error", "timestamp": 1718448000, "platform": "linux", "language": "python", "framework": "django", "notifier": { "name": "pyrollbar", "version": "1.4.0" }, "body": { "trace": { "frames": [ { "filename": "/app/myapp/views.py", "method": "get_user", "lineno": 42, "code": "user = User.objects.get(id=user_id)" } ], "exception": { "class": "django.core.exceptions.ObjectDoesNotExist", "message": "User matching query does not exist.", "description": "User matching query does not exist." } } }, "request": { "url": "https://example.com/api/users/999", "method": "GET", "headers": { "User-Agent": "curl/7.64.1", "Accept": "*/*" }, "GET": {}, "user_ip": "203.0.113.42" }, "person": { "id": "123", "email": "user@example.com" }, "server": { "host": "web-server-1", "pid": 12345, "root": "/app", "branch": "main" }, "custom": { "user_id": 999, "action": "fetch_user" }, "uuid": "f2cc8e32-2e8f-46c9-9e2e-f2cc8e32f2cc" } } ``` -------------------------------- ### ScrubTransform with Custom Suffixes Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Initialize `ScrubTransform` with custom suffix patterns to redact sensitive data. This example redacts keys ending with 'password' or 'api_key'. ```python from rollbar.lib.transforms.scrub import ScrubTransform # Create with custom patterns scrubber = ScrubTransform(suffixes=[('password',), ('api_key',)]) # Redacts any key ending with 'password' or 'api_key' data = {'user_password': 'secret123', 'api_key': 'sk_live_xyz'} # Result: {'user_password': '***', 'api_key': '****'} ``` -------------------------------- ### Custom Transforms for Data Transformation Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Example demonstrating how to define and use a custom transform class to modify data before it's sent to Rollbar. This includes setting a priority and implementing the `transform_dict` method. ```python from rollbar.lib.transform import Transform class CustomTransform(Transform): priority = 25 def transform_dict(self, o, key=None): return o rollbar.init( 'TOKEN', 'production', custom_transforms=[CustomTransform()], batch_transforms=False, shortener_keys=[ ('body', 'custom_data', '*') ] ) ``` -------------------------------- ### Configuring Local Variable Capture Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Example of initializing pyrollbar with custom local variable capture settings, including enabling capture, safe representation, and adjusting size limits for strings, dictionaries, and lists. ```python rollbar.init( 'TOKEN', 'production', locals={ 'enabled': True, 'safe_repr': True, 'sizes': { 'maxstring': 200, 'maxdict': 20, 'maxlist': 20 }, 'safelisted_types': [int, str, bool, list, dict] } ) ``` -------------------------------- ### Example Log for Server Errors Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/error-handling.md Illustrates the log output when pyrollbar encounters a server error (e.g., HTTP 502) from the Rollbar API. These errors are logged but not retried. ```text WARNING Got unexpected status code from Rollbar api: 502 Response: {error response body} ``` -------------------------------- ### Configuring Exception Level Filters Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Example of initializing pyrollbar with custom exception level filters. This allows mapping specific exception classes to different reporting levels, such as 'warning', 'info', or 'ignored'. ```python rollbar.init( 'TOKEN', 'production', exception_level_filters=[ (ValueError, 'warning'), (KeyError, 'info'), ('django.http.Http404', 'ignored'), ] ) ``` -------------------------------- ### Disabling Basic Logging Configuration Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Example of initializing pyrollbar in environments like Flask or Django where logging is already configured. Setting `allow_logging_basic_config` to `False` prevents pyrollbar from reconfiguring the logging system. ```python # For Flask/Django where logging is already configured rollbar.init( 'TOKEN', 'production', allow_logging_basic_config=False # Don't reconfigure logging ) ``` -------------------------------- ### Configuring Error Reporting Behavior Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Example of initializing pyrollbar with custom settings for error reporting. This includes controlling whether all rate-limited items are logged and whether the full payload is logged on API errors. ```python rollbar.init( 'TOKEN', 'production', log_all_rate_limited_items=False, # Only log first 429 log_payload_on_error=True # Log payloads on error ) ``` -------------------------------- ### Example Generated Execution Scope IDs Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Illustrates the format of generated execution scope IDs, which are 32-character hexadecimal strings representing 128 random bits. ```text # Example generated IDs: # 'a1b2c3d4e5f6789012345678901234ab' # '0123456789abcdef0123456789abcdef' ``` -------------------------------- ### Pyramid WSGI Middleware Configuration (paste deploy) Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Configure Rollbar as a WSGI filter using paste deploy for Pyramid applications. This example shows how to set the access token, environment, and root path. ```ini [filter:rollbar] use = egg:rollbar#pyramid access_token = YOUR_ACCESS_TOKEN environment = production root = /var/www/myapp [pipeline:main] pipeline = rollbar main ``` -------------------------------- ### Message Payload Example Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/types-and-payloads.md This is a typical payload structure for reporting a general message or informational event. It includes environment details, message content, request context, and person data. ```json { "access_token": "aaaabbbbccccddddeeeeffff00001111", "data": { "environment": "production", "level": "info", "timestamp": 1718448000, "platform": "linux", "language": "python", "framework": "django", "notifier": { "name": "pyrollbar", "version": "1.4.0" }, "body": { "message": { "body": "User logged in successfully" } }, "request": { "url": "https://example.com/login", "method": "POST", "headers": { "User-Agent": "Mozilla/5.0", "Content-Type": "application/json" }, "user_ip": "203.0.113.99" }, "person": { "id": "456", "username": "alice" }, "server": { "host": "web-server-1", "pid": 12345 }, "custom": { "session_id": "sess_abc123" }, "uuid": "e1dd7c21-1f7e-45b8-8d1d-e1dd7c21e1dd" } } ``` -------------------------------- ### Run Tests Source: https://github.com/rollbar/pyrollbar/blob/master/README.md Execute the project's tests using the setup.py script. ```bash python setup.py test ``` -------------------------------- ### Troubleshooting Missing Access Token Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Demonstrates the correct way to provide an access token when encountering a 'missing access_token' error. ```bash # This fails: rollbar -e production error "Message" # You must provide token: rollbar -t TOKEN -e production error "Message" ``` -------------------------------- ### Troubleshooting Missing Environment Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Shows the correct way to specify an environment when encountering a 'missing environment' error. ```bash # This fails: rollbar -t TOKEN error "Message" # You must provide environment: rollbar -t TOKEN -e production error "Message" ``` -------------------------------- ### Using Environment Variables for Token and Environment Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md Demonstrates how to use environment variables to provide the access token and environment to the Rollbar CLI. ```bash export ROLLBAR_TOKEN=aaaabbbbccccddddeeeeffff00001111 export ROLLBAR_ENV=production rollbar -t $ROLLBAR_TOKEN -e $ROLLBAR_ENV error "Error message" ``` -------------------------------- ### Get Current Unix Timestamp Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/types-and-payloads.md Obtain the current time as a Unix timestamp (seconds since the epoch). ```python import time int(time.time()) # 1718448000 ``` -------------------------------- ### Server Structure Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/types-and-payloads.md Contains server and environment details, such as hostname, process ID, command-line arguments, and application root. ```json { 'host': str, # Hostname 'pid': int, # Process ID 'argv': list, # Command-line arguments (optional) 'root': str, # Application root path (optional) 'branch': str, # Git branch name (optional) 'history': list, # Log history (optional, from logging handler) } ``` -------------------------------- ### Configure Proxy Settings Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Initialize Rollbar with proxy settings for secure communication. Ensure to provide the correct proxy URL, username, and password if authentication is required. ```python rollbar.init( 'TOKEN', 'production', http_proxy='http://proxy.corp.com:8080', http_proxy_user='username', http_proxy_password='password' ) ``` -------------------------------- ### Install Rollbar LoggerMiddleware for Starlette Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Add the LoggerMiddleware to your Starlette application to log all incoming requests to Rollbar at the info level. ```python app.add_middleware(LoggerMiddleware) ``` -------------------------------- ### Initialize and Report Exception Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/README.md Basic usage for initializing the Rollbar client with an access token and environment, and reporting an unhandled exception. ```python import rollbar # Initialize rollbar.init('YOUR_ACCESS_TOKEN', 'production') # Report exception try: risky_operation() except: rollbar.report_exc_info() ``` -------------------------------- ### Initialize Pyrollbar Client Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/core-api.md Initializes the Rollbar client with your project's access token and environment. Additional configuration options can be passed as keyword arguments. ```python import rollbar rollbar.init('aaaabbbbccccddddeeeeffff00001111', environment='production') ``` ```python rollbar.init( 'aaaabbbbccccddddeeeeffff00001111', environment='production', root='/app', branch='main', enabled=True, capture_ip=True ) ``` -------------------------------- ### rollbar.init Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/core-api.md Initializes the Rollbar client with configuration settings. This function must be called once before reporting any events. ```APIDOC ## rollbar.init ### Description Initializes the Rollbar client with configuration settings. Must be called once before reporting any events. ### Method `init(access_token, environment='production', scrub_fields=None, url_fields=None, **kw)` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **access_token** (str) - Required - Rollbar project access token from https://rollbar.com/settings/projects * **environment** (str) - Optional - Environment name (production, staging, development, etc.) * **scrub_fields** (list[str]) - Optional - List of field names to redact in payloads (overrides default scrub_fields) * **url_fields** (list[str]) - Optional - List of URL field names to scrub query parameters from (overrides defaults) * **\[kw\]** (dict) - Optional - Additional configuration options (merged with SETTINGS) ### Request Example ```python import rollbar rollbar.init('aaaabbbbccccddddeeeeffff00001111', environment='production') # With additional configuration rollbar.init( 'aaaabbbbccccddddeeeeffff00001111', environment='production', root='/app', branch='main', enabled=True, capture_ip=True ) ``` ### Response #### Success Response (200) * None #### Response Example * None ``` -------------------------------- ### Get Current Starlette Request Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Retrieve the current Starlette request object from context. This function is available in the Starlette integration. ```python from rollbar.contrib.starlette.requests import get_current_request # In a route handler request = get_current_request() if request: print(request.url, request.method) ``` -------------------------------- ### Get Current Session Data Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Retrieves the current session data, which includes session_id and/or execution_scope_id. This is called when building payloads. ```python from rollbar.lib.session import get_current_session # In error handler session = get_current_session() # Returns: [{'key': 'execution_scope_id', 'value': '...'}] # Use in payload payload = { 'data': { 'attributes': session, ... } } ``` -------------------------------- ### Reset Current Session Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Clears the current session data. Call this at the end of request handling, for example, in Flask's after_request handler. ```python from rollbar.lib.session import reset_current_session # In Flask after_request handler @app.after_request def cleanup_session(response): reset_current_session() return response ``` -------------------------------- ### set_current_session Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Sets the current session data by parsing W3C baggage headers. This function should be called at the start of request handling to establish the session context. ```APIDOC ## set_current_session(headers: dict[str, str]) -> None ### Description Sets the current session data by parsing W3C baggage headers. Called at the start of request handling. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **headers** (dict[str, str]) - Required - HTTP request headers (case-insensitive keys) ### Returns None ### Behavior - Parses the `baggage` header for session information - Generates a new execution scope ID if missing - Stores in context variable (for async) and thread-local storage (for sync) ### Header Format The baggage header uses comma-separated key=value pairs: ``` baggage: rollbar.session.id=sess_abc123, rollbar.execution.scope.id=scope_xyz789 ``` ### Example ```python from rollbar.lib.session import set_current_session # In a Flask request handler from flask import request @app.before_request def setup_session(): set_current_session(dict(request.headers)) # Or in a FastAPI middleware @app.middleware("http") async def middleware(request, call_next): set_current_session(dict(request.headers)) return await call_next(request) ``` ``` -------------------------------- ### Set Current Session in Flask Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Sets the current session data by parsing W3C baggage headers. Call this at the start of request handling in Flask. ```python from rollbar.lib.session import set_current_session from flask import request @app.before_request def setup_session(): set_current_session(dict(request.headers)) ``` -------------------------------- ### Configure User Information Capture Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Initialize Rollbar to capture user-specific data. Control IP address, email, and username capture based on privacy and debugging needs. ```python rollbar.init( 'TOKEN', 'production', capture_ip='anonymize', # Mask user IPs capture_email=True, # Include email if available capture_username=False # Don't include username ) ``` -------------------------------- ### Register and Use Payload Handler to Add Deployment Info Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/events-filters.md Demonstrates registering a payload handler to automatically inject custom data, such as a deployment ID from an environment variable, into every reported payload. ```python import rollbar from rollbar import events def add_deployment_info(payload, **kw): payload['data']['custom'] = payload['data'].get('custom', {}) payload['data']['custom']['deployment_id'] = os.environ.get('DEPLOYMENT_ID') return payload events.add_payload_handler(add_deployment_info) rollbar.init('TOKEN', 'production') # All payloads will include deployment_id in custom data rollbar.report_message('App started') ``` -------------------------------- ### Add Exception Handlers at Specific Positions Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/events-filters.md Demonstrates how to add exception info handlers to run either first or last in the processing order. ```python events.add_exception_info_handler(handler_early, pos=0) # Run first events.add_exception_info_handler(handler_late, pos=None) # Run last ``` -------------------------------- ### Enable Batched Transforms Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Configuration to enable batch processing of transformations during Rollbar initialization. ```python rollbar.init(..., batch_transforms=True) ``` -------------------------------- ### Custom Transform Example: MaskEmailTransform Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md A custom transform that masks email addresses by replacing the local part with asterisks, preserving the first and last characters. It runs after the shortener and before serialization. ```python from rollbar.lib.transform import Transform import rollbar class MaskEmailTransform(Transform): """Mask email addresses in payloads""" priority = 25 # Run after shortener, before serializer def transform_unicode(self, o, key=None): # Check if value looks like an email if '@' in o and '.' in o: local, domain = o.split('@', 1) # Mask local part masked = local[0] + '*' * (len(local) - 2) + local[-1] return f"{masked}@{domain}" return o ``` -------------------------------- ### Get Current Request Object in Flask Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/core-api.md Retrieves the current request object from the Flask web framework context. This is automatically called when building payloads if no explicit request is provided. ```python import rollbar from flask import Flask app = Flask(__name__) @app.route('/api/users') def get_users(): # Request is automatically detected current_request = rollbar.get_request() if current_request: print(current_request.method, current_request.path) return {'users': []} ``` -------------------------------- ### Get Current FastAPI Request Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Retrieve the current Starlette/FastAPI request object from context within a route handler. This is useful for logging request details or including them in error reports. ```python from rollbar.contrib.fastapi import get_current_request import rollbar # In a route handler @app.get('/api/data') async def get_data(): request = get_current_request() if request: print(request.url, request.method) try: data = fetch_data() except: # Request is automatically included rollbar.report_exc_info() return data ``` -------------------------------- ### RollbarHandler Constructor Parameters Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/logging-handler.md Defines the parameters for initializing the RollbarHandler, including access token, environment, log levels, and history tracking settings. ```python RollbarHandler( access_token=None, environment=None, level=logging.INFO, history_size=10, history_level=logging.DEBUG, **kw ) ``` -------------------------------- ### Initialize Rollbar with Environment-Specific Configuration Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Configure Rollbar using environment variables for access token and environment. The `enabled` flag can be used to conditionally disable Rollbar, for example, in a test environment. ```python import os import rollbar env = os.getenv('ENVIRONMENT', 'development') rollbar.init( os.getenv('ROLLBAR_ACCESS_TOKEN'), environment=env, enabled=(env != 'test'), # Disable in test environment root='/app' ) ``` -------------------------------- ### Basic Rollbar CLI Syntax Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/cli-reference.md The basic syntax for invoking the Rollbar CLI command. ```bash rollbar COMMAND [MESSAGE] ``` -------------------------------- ### Custom Transform Class Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/transforms-configuration.md Define a custom transform by inheriting from `Transform` and overriding specific transform methods like `transform_dict`. This example customizes dictionary processing for keys ending in 'metadata'. ```python from rollbar.lib.transform import Transform class CustomTransform(Transform): priority = 25 # Run between serialize and scrub def transform_dict(self, o, key=None): # Custom dict processing if key and key[-1] == 'metadata': return {k: v for k, v in o.items() if v is not None} return o ``` -------------------------------- ### Initialize Rollbar Reporter Middleware for FastAPI Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Adds the Rollbar ReporterMiddleware to a FastAPI application to catch and report exceptions. Ensure Rollbar is initialized with your access token and environment before adding the middleware. ```python from fastapi import FastAPI from rollbar.contrib.fastapi import ReporterMiddleware import rollbar app = FastAPI() rollbar.init('YOUR_ACCESS_TOKEN', 'production') app.add_middleware(ReporterMiddleware) ``` -------------------------------- ### Parse Session Request Baggage Headers Without Header Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Parses W3C baggage headers to extract session information. This example demonstrates the behavior when no baggage header is present and generation is disabled. ```python session = parse_session_request_baggage_headers({}) # Returns: [] ``` -------------------------------- ### Configure Logging for Rate Limited Items Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/error-handling.md Configure pyrollbar to log all rate-limited items or only the first one. This setting controls the verbosity of warnings when the API rate limits are hit. ```python rollbar.init( 'TOKEN', 'production', log_all_rate_limited_items=True, # Log every 429 (default) # or set to False to log only the first 429 ) ``` -------------------------------- ### Configure Code Information Capture Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/configuration.md Initialize Rollbar with application-specific code details. This helps in pinpointing issues to specific code versions or branches. ```python import os import rollbar rollbar.init( 'TOKEN', 'production', root='/app', branch=os.getenv('GIT_BRANCH', 'main'), code_version=os.getenv('APP_VERSION', '1.0.0'), host=os.getenv('HOSTNAME') ) ``` -------------------------------- ### Commit Changes Source: https://github.com/rollbar/pyrollbar/blob/master/README.md Stage and commit your code changes with a descriptive message. ```bash git commit -am 'Added some feature' ``` -------------------------------- ### Create Feature Branch Source: https://github.com/rollbar/pyrollbar/blob/master/README.md Use this command to create a new branch for your feature development. ```bash git checkout -b my-new-feature ``` -------------------------------- ### Parse Session Request Baggage Headers with Session Data Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Parses W3C baggage headers to extract session information. This example shows a case where both session ID and execution scope ID are present. ```python headers = { 'baggage': 'rollbar.session.id=sess_123, rollbar.execution.scope.id=scope_456' } session = parse_session_request_baggage_headers(headers) # Returns: [ # {'key': 'session_id', 'value': 'sess_123'}, # {'key': 'execution_scope_id', 'value': 'scope_456'} # ] ``` -------------------------------- ### Parse Session Request Baggage Headers with Missing Scope ID and Generation Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/session-tracking.md Parses W3C baggage headers to extract session information. This example shows how a new execution scope ID is generated when missing and generate_missing is True. ```python headers = {'baggage': 'rollbar.session.id=sess_789'} session = parse_session_request_baggage_headers(headers, generate_missing=True) # Returns: [ # {'key': 'session_id', 'value': 'sess_789'}, # {'key': 'execution_scope_id', 'value': ''} # ] ``` -------------------------------- ### FastAPI Integration Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/README.md Integrate Rollbar with FastAPI by adding the ReporterMiddleware and using add_to. This ensures all routes are logged and exceptions are reported. ```python from fastapi import FastAPI from rollbar.contrib.fastapi import ReporterMiddleware, add_to import rollbar app = FastAPI() rollbar.init('TOKEN', 'production') app.add_middleware(ReporterMiddleware) add_to(app) # Log all routes ``` -------------------------------- ### Configure Rollbar Handler with Formatter Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/logging-handler.md Set up the RollbarHandler with a custom logging formatter to include timestamps, logger name, level, and message in log payloads. ```python import logging from rollbar.logger import RollbarHandler handler = RollbarHandler('TOKEN', 'production') formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) handler.setFormatter(formatter) logger = logging.getLogger(__name__) logger.addHandler(handler) ``` -------------------------------- ### Configure Django Middleware Excluding 404s Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/framework-integrations.md Configures Django to use RollbarNotifierMiddlewareExcluding404, which reports exceptions but excludes 404 errors. Add this to your MIDDLEWARE list in settings.py. ```python MIDDLEWARE = [ 'rollbar.contrib.django.middleware.RollbarNotifierMiddlewareExcluding404', ] ``` -------------------------------- ### Register and Use Exception Info Handler to Ignore Timeouts Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/events-filters.md Demonstrates how to register a custom exception info handler to ignore specific exceptions, like requests.Timeout, preventing them from being reported to Rollbar. ```python import rollbar from rollbar import events def ignore_timeouts(exc_info, **kw): cls, exc, trace = exc_info if cls is requests.Timeout: return False # Don't report timeouts return exc_info rollbar.events.add_exception_info_handler(ignore_timeouts) rollbar.init('TOKEN', 'production') try: requests.get('http://slow-api.example.com', timeout=1) except requests.Timeout: # This is not reported due to the handler rollbar.report_exc_info() ``` -------------------------------- ### Request Structure Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/types-and-payloads.md Contains HTTP request details for context, including URL, method, headers, query parameters, and form data. ```json { 'url': str, # Full request URL 'method': str, # HTTP method (GET, POST, etc.) 'headers': dict, # HTTP headers 'GET': dict, # Query parameters 'POST': dict, # Form data or JSON body 'json': dict, # Parsed JSON (if applicable) 'params': dict, # URL parameters (FastAPI) 'user_ip': str, # Client IP address 'body': str, # Raw request body (if include_request_body=True) } ``` -------------------------------- ### Advanced Rollbar Configuration Source: https://github.com/rollbar/pyrollbar/blob/master/_autodocs/README.md Configure Rollbar with advanced options including root path, branch, handler type, IP capture, field scrubbing, local variable capture, and exception level filtering. ```python import rollbar rollbar.init( 'TOKEN', 'production', root='/app', branch='main', handler='thread', capture_ip='anonymize', scrub_fields=['password', 'api_key'], locals={'enabled': True, 'sizes': {'maxstring': 200}}, exception_level_filters=[ ('ValueError', 'warning'), ('django.http.Http404', 'ignored'), ] ) ```