Skip to main content

Sentry Handler

A custom Sentry handler that provides PII filtering, event deduplication, and rate limiting capabilities for Sentry error reporting.

Features

  • PII (Personally Identifiable Information) filtering
  • Event deduplication using Redis
  • Rate limiting for error propagation
  • Custom exception filtering
  • Logger message filtering
  • EC2 instance information tracking

Installation

pip install rate-limiter

Usage

Here's how to initialize Sentry with the SentryHandler:

import sentry_sdk
from redis import Redis
from rate_limiter.sentry_helper import SentryHandler

# Initialize Redis connection
redis_client = Redis(
    host='your-redis-host',
    port=6379,
    db=0
)

# Initialize SentryHandler
sentry_handler = SentryHandler(
    redis_connection=redis_client,
    git_commit_hash='your-git-commit-hash'  # Optional
)

# Initialize Sentry with the handler
sentry_sdk.init(
    dsn="your-sentry-dsn",
    before_send=sentry_handler.before_send_sentry_handler,
    # Add other Sentry configuration options as needed
)

Configuration Options

The SentryHandler accepts the following parameters:

Required Parameters

  • redis_connection: Redis connection instance
    redis_client = Redis(host='localhost', port=6379, db=0)
    

Optional Parameters

  • git_commit_hash: Git commit hash for tagging events

    git_commit_hash = "a1b2c3d4e5"  # Will be truncated to first 10 characters
    
  • pii_regex_patterns: Custom PII regex patterns to mask sensitive information

    pii_regex_patterns = {
        "email": r"([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)",
        "phone": r"(\+\d{1,3}[- ]?)?\d{10}[\s , )]",
        "pan": r"[A-Z]{5}[0-9]{4}[A-Z]{1}",
        "aadhar": r"[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}[" " , . )]",
        "recording_url": r'[https?: // " ]\S+\.mp3[ \ {t1} . , " ]?'
    }
    
  • exclude_exception_classes: Set of exception classes to exclude from reporting

    exclude_exception_classes = {
        "ConnectionError",
        "TimeoutError",
        "ValidationError"
    }
    
  • exclude_exception_msg_prefixes: List of exception message prefixes to exclude

    exclude_exception_msg_prefixes = [
        "Invalid input",
        "Connection refused",
        "Timeout"
    ]
    
  • silence_logger_messages: Dictionary mapping logger names to lists of message prefixes to silence

    silence_logger_messages = {
        "elasticapm.transport": [
            "Failed to submit message",
            "Unable to reach APM Server"
        ],
        "your.custom.logger": [
            "Ignorable error",
            "Expected failure"
        ]
    }
    
  • propagation_series: Set of numbers for rate limiting propagation

    # Default restricted series
    propagation_series = {1, 2, 4, 8, 16, 32, 64, 128, 256}
    
    # Alternative standard series
    propagation_series = {1, 2, 3, 4, 9, 16, 25, 36, 49}
    

Features in Detail

PII Filtering

Automatically masks sensitive information in error reports using configurable regex patterns. For example:

  • Email addresses: user@example.com → user@****
  • Phone numbers: +91 9876543210 → +91 9876****
  • PAN numbers: ABCDE1234F → ABCDE****
  • Aadhar numbers: 1234 5678 9012 → 1234 **** ****

Event Deduplication

Uses Redis to track and deduplicate similar errors, reducing noise in your Sentry dashboard. Each unique error is tracked with a hash and timestamp.

Rate Limiting

Controls the frequency of error propagation to Sentry using a configurable series of numbers. For example, with the default restricted series:

  • First occurrence: Always sent
  • Second occurrence: Sent
  • Third occurrence: Skipped
  • Fourth occurrence: Sent
  • And so on...

Exception Filtering

Filters out specific exception classes and messages based on configurable rules. For example:

# These exceptions will be filtered out
raise ConnectionError("Connection refused")  # Filtered by class
raise ValueError("Invalid input format")     # Filtered by message prefix

Logger Message Filtering

Silences specific logger messages to reduce noise in your error tracking. For example:

logger.error("Failed to submit message")  # Will be silenced if configured
logger.error("Critical system error")     # Will be reported

EC2 Integration

Automatically adds EC2 instance information to error reports when running on AWS infrastructure:

  • Instance ID: i-1234567890abcdef0
  • Instance Name: production-web-server-1

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Metadata

Release files for sentry-rate-limiter 1.0.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sentry-rate-limiter 1.0.6
File Size Uploaded Provenance Actions
sentry_rate_limiter-1.0.6.tar.gz 5.7 kB Without provenance Details for sentry_rate_limiter-1.0.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sentry-rate-limiter 1.0.6
File Interpreter ABI Platform Actions
sentry_rate_limiter-1.0.6-py3-none-any.whl Python 3 none any Details for sentry_rate_limiter-1.0.6-py3-none-any.whl

Total release size: 12.3 kB

Release files / sentry_rate_limiter-1.0.6.tar.gz

Download URL sentry_rate_limiter-1.0.6.tar.gz
Size 5.7 kB
Tags Source
SHA-256 checksum
How to use checksums
72aec0f1188c8f62e9a37b819dc0bdd773a5a4c982e86f827a456ffce5979a80
BLAKE2b-256 checksum
How to use checksums
59ab97f25975fca65a5a4093f925ba4e8f5248db02d1a9f8cdf629b92ff1425b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.5.29

Release files / sentry_rate_limiter-1.0.6-py3-none-any.whl

Download URL sentry_rate_limiter-1.0.6-py3-none-any.whl
Size 6.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a6a88db797607db96354446c7257b1ac2fd87691f041c4ce652570596e3d6319
BLAKE2b-256 checksum
How to use checksums
c457d2cc9bf8550190f89ca44bde5703e40f781532ba1dd47ac7e334a418fed4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.5.29

Security for sentry-rate-limiter 1.0.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page