error-explorer-python


Nameerror-explorer-python JSON
Version 1.0.1 PyPI version JSON
download
home_pagehttps://github.com/Manguet/ErrorReportPythonSDK
SummaryPython SDK for Error Explorer - Capture and report errors automatically
upload_time2025-08-12 15:53:02
maintainerNone
docs_urlNone
authorManguet
requires_python>=3.7
licenseNone
keywords error monitoring debugging logging django flask fastapi python
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Error Explorer Python SDK

Python SDK for Error Explorer - Capture and report errors automatically from your Python applications.

## Installation

```bash
pip install error-explorer-python
# or
poetry add error-explorer-python
```

## Quick Start

### Basic Setup

```python
import error_explorer

# Initialize Error Explorer
error_explorer.init(
    webhook_url="https://error-explorer.com/webhook/project-token",
    project_name="my-python-app",
    environment="production"
)

# Capture exceptions
try:
    risky_operation()
except Exception as e:
    error_explorer.capture_exception(e)

# Capture messages
error_explorer.capture_message("Something happened", "info")
```

### Django Integration

1. **Add to installed apps** (`settings.py`):

```python
INSTALLED_APPS = [
    # ... your other apps
    'error_explorer.integrations.django',
]
```

2. **Add middleware** (`settings.py`):

```python
MIDDLEWARE = [
    'error_explorer.integrations.django.ErrorExplorerMiddleware',
    # ... your other middleware
]
```

3. **Configure Error Explorer** (`settings.py`):

```python
ERROR_EXPLORER = {
    'WEBHOOK_URL': 'https://error-explorer.com/webhook/project-token',
    'PROJECT_NAME': 'my-django-app',
    'ENVIRONMENT': 'production',
    'ENABLED': True,
}

# Optional: Add logging handler
LOGGING = {
    'version': 1,
    'handlers': {
        'error_explorer': {
            'class': 'error_explorer.integrations.django.ErrorExplorerHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['error_explorer'],
            'level': 'ERROR',
        },
    },
}
```

4. **Initialize in your Django app** (`apps.py` or `__init__.py`):

```python
import error_explorer
from django.conf import settings

if hasattr(settings, 'ERROR_EXPLORER'):
    config = settings.ERROR_EXPLORER
    error_explorer.init(
        webhook_url=config['WEBHOOK_URL'],
        project_name=config['PROJECT_NAME'],
        environment=config.get('ENVIRONMENT', 'production'),
        enabled=config.get('ENABLED', True)
    )
```

### Flask Integration

```python
from flask import Flask
import error_explorer
from error_explorer.integrations.flask import capture_exceptions

app = Flask(__name__)

# Initialize Error Explorer
error_explorer.init(
    webhook_url="https://error-explorer.com/webhook/project-token",
    project_name="my-flask-app",
    environment="production"
)

# Set up automatic error capture
capture_exceptions(app)

# Or use the integration class
from error_explorer.integrations.flask import FlaskIntegration
FlaskIntegration(app)

@app.route('/')
def index():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
```

### FastAPI Integration

```python
from fastapi import FastAPI
import error_explorer
from error_explorer.integrations.fastapi import setup_error_explorer

app = FastAPI()

# Initialize Error Explorer
error_explorer.init(
    webhook_url="https://error-explorer.com/webhook/project-token",
    project_name="my-fastapi-app",
    environment="production"
)

# Set up automatic error capture
setup_error_explorer(app)

@app.get("/")
async def root():
    return {"message": "Hello World"}
```

## Configuration

### Required Options

- `webhook_url`: Your Error Explorer webhook URL
- `project_name`: Name of your project

### Optional Options

```python
error_explorer.init(
    webhook_url="https://error-explorer.com/webhook/project-token",
    project_name="my-python-app",
    environment="production",        # Default: "production"
    enabled=True,                    # Default: True
    user_id="user123",              # Optional: Default user ID
    user_email="user@example.com",  # Optional: Default user email
    max_breadcrumbs=50,              # Default: 50
    timeout=5,                       # Default: 5 seconds
    retries=3,                       # Default: 3
    debug=False,                     # Default: False
    before_send=lambda data: data    # Optional: Filter/modify data
)
```

## API Reference

### error_explorer.init(\*\*config)

Initializes the Error Explorer client.

### error_explorer.capture_exception(exception, context=None)

Captures an exception with optional context.

```python
try:
    risky_operation()
except Exception as e:
    error_explorer.capture_exception(e, {
        "user_id": 123,
        "operation": "risky_operation"
    })
```

### error_explorer.capture_message(message, level="info", context=None)

Captures a custom message.

```python
error_explorer.capture_message("User logged in", "info", {
    "user_id": 123
})
```

### error_explorer.add_breadcrumb(message, category="custom", level="info", data=None)

Adds a breadcrumb for debugging context.

```python
error_explorer.add_breadcrumb("User clicked button", "ui", "info", {
    "button_id": "submit-btn"
})
```

### error_explorer.set_user(user)

Sets user context for all future error reports.

```python
error_explorer.set_user({
    "id": 123,
    "email": "user@example.com",
    "username": "john_doe"
})
```

## Advanced Usage

### Custom Error Context

```python
from error_explorer import ErrorExplorer

client = ErrorExplorer(
    webhook_url="https://error-explorer.com/webhook/project-token",
    project_name="my-app"
)

# Add breadcrumbs for context
client.add_breadcrumb("User started checkout", "user_action")
client.add_breadcrumb("Payment method selected", "user_action")

try:
    process_payment()
except Exception as e:
    client.capture_exception(e, {
        "payment_method": "credit_card",
        "amount": 99.99,
        "currency": "USD"
    })
```

### Database Query Monitoring

```python
import time

def execute_query(sql, params=None):
    start_time = time.time()
    
    error_explorer.add_breadcrumb(f"Executing query: {sql[:50]}...", "database")
    
    try:
        result = database.execute(sql, params)
        duration = time.time() - start_time
        
        error_explorer.add_breadcrumb(
            f"Query completed in {duration:.3f}s", 
            "database", 
            "info",
            {"duration": duration, "rows": len(result)}
        )
        
        return result
    except Exception as e:
        duration = time.time() - start_time
        error_explorer.capture_exception(e, {
            "query": sql,
            "params": params,
            "duration": duration
        })
        raise
```

### Before Send Hook

```python
def filter_sensitive_data(data):
    """Filter out sensitive information before sending."""
    if data.context and 'password' in data.context:
        data.context['password'] = '[FILTERED]'
    
    # Don't send errors from development environment
    if data.environment == 'development':
        return None
    
    return data

error_explorer.init(
    webhook_url="https://error-explorer.com/webhook/project-token",
    project_name="my-app",
    before_send=filter_sensitive_data
)
```

## CLI Usage

The package includes a CLI tool for testing:

```bash
# Test connection
error-explorer test https://error-explorer.com/webhook/project-token my-project

# Show version
error-explorer version
```

## Environment Variables

You can use environment variables for configuration:

```bash
ERROR_EXPLORER_WEBHOOK_URL=https://error-explorer.com/webhook/project-token
ERROR_EXPLORER_PROJECT_NAME=my-python-app
ERROR_EXPLORER_ENVIRONMENT=production
```

```python
import os
import error_explorer

error_explorer.init(
    webhook_url=os.environ['ERROR_EXPLORER_WEBHOOK_URL'],
    project_name=os.environ['ERROR_EXPLORER_PROJECT_NAME'],
    environment=os.environ.get('ERROR_EXPLORER_ENVIRONMENT', 'production')
)
```

## Framework-Specific Examples

### Django with Custom User Context

```python
# middleware.py
from django.utils.deprecation import MiddlewareMixin
import error_explorer

class UserContextMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.user.is_authenticated:
            error_explorer.set_user({
                "id": request.user.id,
                "email": request.user.email,
                "username": request.user.username,
                "is_staff": request.user.is_staff
            })
```

### Flask with Request Context

```python
from flask import Flask, request, g
import error_explorer

app = Flask(__name__)

@app.before_request
def before_request():
    error_explorer.add_breadcrumb(
        f"{request.method} {request.path}",
        "http"
    )
    
    if hasattr(g, 'user'):
        error_explorer.set_user({
            "id": g.user.id,
            "email": g.user.email
        })
```

## Troubleshooting

### Errors not appearing in dashboard
1. Check that the webhook URL is correct
2. Verify that Error Explorer is running and accessible
3. Enable debug mode: `error_explorer.init(..., debug=True)`
4. Check the console for any Error Explorer related messages

### Performance considerations
1. Error Explorer sends data asynchronously by default
2. Adjust `timeout` and `retries` based on your needs
3. Use `before_send` to filter out unnecessary errors
4. Consider rate limiting in high-traffic applications

## Requirements

- Python 3.7+
- requests
- Optional: Django 3.0+, Flask 1.0+, FastAPI 0.65.0+

## License

MIT

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Manguet/ErrorReportPythonSDK",
    "name": "error-explorer-python",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "error monitoring debugging logging django flask fastapi python",
    "author": "Manguet",
    "author_email": "benjamin.manguet@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/1e/08/ff6423dcdf84f219eb1b675fb27f30d082f3f2befbb3bef82bfd3a346714/error-explorer-python-1.0.1.tar.gz",
    "platform": null,
    "description": "# Error Explorer Python SDK\n\nPython SDK for Error Explorer - Capture and report errors automatically from your Python applications.\n\n## Installation\n\n```bash\npip install error-explorer-python\n# or\npoetry add error-explorer-python\n```\n\n## Quick Start\n\n### Basic Setup\n\n```python\nimport error_explorer\n\n# Initialize Error Explorer\nerror_explorer.init(\n    webhook_url=\"https://error-explorer.com/webhook/project-token\",\n    project_name=\"my-python-app\",\n    environment=\"production\"\n)\n\n# Capture exceptions\ntry:\n    risky_operation()\nexcept Exception as e:\n    error_explorer.capture_exception(e)\n\n# Capture messages\nerror_explorer.capture_message(\"Something happened\", \"info\")\n```\n\n### Django Integration\n\n1. **Add to installed apps** (`settings.py`):\n\n```python\nINSTALLED_APPS = [\n    # ... your other apps\n    'error_explorer.integrations.django',\n]\n```\n\n2. **Add middleware** (`settings.py`):\n\n```python\nMIDDLEWARE = [\n    'error_explorer.integrations.django.ErrorExplorerMiddleware',\n    # ... your other middleware\n]\n```\n\n3. **Configure Error Explorer** (`settings.py`):\n\n```python\nERROR_EXPLORER = {\n    'WEBHOOK_URL': 'https://error-explorer.com/webhook/project-token',\n    'PROJECT_NAME': 'my-django-app',\n    'ENVIRONMENT': 'production',\n    'ENABLED': True,\n}\n\n# Optional: Add logging handler\nLOGGING = {\n    'version': 1,\n    'handlers': {\n        'error_explorer': {\n            'class': 'error_explorer.integrations.django.ErrorExplorerHandler',\n        },\n    },\n    'loggers': {\n        'django': {\n            'handlers': ['error_explorer'],\n            'level': 'ERROR',\n        },\n    },\n}\n```\n\n4. **Initialize in your Django app** (`apps.py` or `__init__.py`):\n\n```python\nimport error_explorer\nfrom django.conf import settings\n\nif hasattr(settings, 'ERROR_EXPLORER'):\n    config = settings.ERROR_EXPLORER\n    error_explorer.init(\n        webhook_url=config['WEBHOOK_URL'],\n        project_name=config['PROJECT_NAME'],\n        environment=config.get('ENVIRONMENT', 'production'),\n        enabled=config.get('ENABLED', True)\n    )\n```\n\n### Flask Integration\n\n```python\nfrom flask import Flask\nimport error_explorer\nfrom error_explorer.integrations.flask import capture_exceptions\n\napp = Flask(__name__)\n\n# Initialize Error Explorer\nerror_explorer.init(\n    webhook_url=\"https://error-explorer.com/webhook/project-token\",\n    project_name=\"my-flask-app\",\n    environment=\"production\"\n)\n\n# Set up automatic error capture\ncapture_exceptions(app)\n\n# Or use the integration class\nfrom error_explorer.integrations.flask import FlaskIntegration\nFlaskIntegration(app)\n\n@app.route('/')\ndef index():\n    return 'Hello World!'\n\nif __name__ == '__main__':\n    app.run()\n```\n\n### FastAPI Integration\n\n```python\nfrom fastapi import FastAPI\nimport error_explorer\nfrom error_explorer.integrations.fastapi import setup_error_explorer\n\napp = FastAPI()\n\n# Initialize Error Explorer\nerror_explorer.init(\n    webhook_url=\"https://error-explorer.com/webhook/project-token\",\n    project_name=\"my-fastapi-app\",\n    environment=\"production\"\n)\n\n# Set up automatic error capture\nsetup_error_explorer(app)\n\n@app.get(\"/\")\nasync def root():\n    return {\"message\": \"Hello World\"}\n```\n\n## Configuration\n\n### Required Options\n\n- `webhook_url`: Your Error Explorer webhook URL\n- `project_name`: Name of your project\n\n### Optional Options\n\n```python\nerror_explorer.init(\n    webhook_url=\"https://error-explorer.com/webhook/project-token\",\n    project_name=\"my-python-app\",\n    environment=\"production\",        # Default: \"production\"\n    enabled=True,                    # Default: True\n    user_id=\"user123\",              # Optional: Default user ID\n    user_email=\"user@example.com\",  # Optional: Default user email\n    max_breadcrumbs=50,              # Default: 50\n    timeout=5,                       # Default: 5 seconds\n    retries=3,                       # Default: 3\n    debug=False,                     # Default: False\n    before_send=lambda data: data    # Optional: Filter/modify data\n)\n```\n\n## API Reference\n\n### error_explorer.init(\\*\\*config)\n\nInitializes the Error Explorer client.\n\n### error_explorer.capture_exception(exception, context=None)\n\nCaptures an exception with optional context.\n\n```python\ntry:\n    risky_operation()\nexcept Exception as e:\n    error_explorer.capture_exception(e, {\n        \"user_id\": 123,\n        \"operation\": \"risky_operation\"\n    })\n```\n\n### error_explorer.capture_message(message, level=\"info\", context=None)\n\nCaptures a custom message.\n\n```python\nerror_explorer.capture_message(\"User logged in\", \"info\", {\n    \"user_id\": 123\n})\n```\n\n### error_explorer.add_breadcrumb(message, category=\"custom\", level=\"info\", data=None)\n\nAdds a breadcrumb for debugging context.\n\n```python\nerror_explorer.add_breadcrumb(\"User clicked button\", \"ui\", \"info\", {\n    \"button_id\": \"submit-btn\"\n})\n```\n\n### error_explorer.set_user(user)\n\nSets user context for all future error reports.\n\n```python\nerror_explorer.set_user({\n    \"id\": 123,\n    \"email\": \"user@example.com\",\n    \"username\": \"john_doe\"\n})\n```\n\n## Advanced Usage\n\n### Custom Error Context\n\n```python\nfrom error_explorer import ErrorExplorer\n\nclient = ErrorExplorer(\n    webhook_url=\"https://error-explorer.com/webhook/project-token\",\n    project_name=\"my-app\"\n)\n\n# Add breadcrumbs for context\nclient.add_breadcrumb(\"User started checkout\", \"user_action\")\nclient.add_breadcrumb(\"Payment method selected\", \"user_action\")\n\ntry:\n    process_payment()\nexcept Exception as e:\n    client.capture_exception(e, {\n        \"payment_method\": \"credit_card\",\n        \"amount\": 99.99,\n        \"currency\": \"USD\"\n    })\n```\n\n### Database Query Monitoring\n\n```python\nimport time\n\ndef execute_query(sql, params=None):\n    start_time = time.time()\n    \n    error_explorer.add_breadcrumb(f\"Executing query: {sql[:50]}...\", \"database\")\n    \n    try:\n        result = database.execute(sql, params)\n        duration = time.time() - start_time\n        \n        error_explorer.add_breadcrumb(\n            f\"Query completed in {duration:.3f}s\", \n            \"database\", \n            \"info\",\n            {\"duration\": duration, \"rows\": len(result)}\n        )\n        \n        return result\n    except Exception as e:\n        duration = time.time() - start_time\n        error_explorer.capture_exception(e, {\n            \"query\": sql,\n            \"params\": params,\n            \"duration\": duration\n        })\n        raise\n```\n\n### Before Send Hook\n\n```python\ndef filter_sensitive_data(data):\n    \"\"\"Filter out sensitive information before sending.\"\"\"\n    if data.context and 'password' in data.context:\n        data.context['password'] = '[FILTERED]'\n    \n    # Don't send errors from development environment\n    if data.environment == 'development':\n        return None\n    \n    return data\n\nerror_explorer.init(\n    webhook_url=\"https://error-explorer.com/webhook/project-token\",\n    project_name=\"my-app\",\n    before_send=filter_sensitive_data\n)\n```\n\n## CLI Usage\n\nThe package includes a CLI tool for testing:\n\n```bash\n# Test connection\nerror-explorer test https://error-explorer.com/webhook/project-token my-project\n\n# Show version\nerror-explorer version\n```\n\n## Environment Variables\n\nYou can use environment variables for configuration:\n\n```bash\nERROR_EXPLORER_WEBHOOK_URL=https://error-explorer.com/webhook/project-token\nERROR_EXPLORER_PROJECT_NAME=my-python-app\nERROR_EXPLORER_ENVIRONMENT=production\n```\n\n```python\nimport os\nimport error_explorer\n\nerror_explorer.init(\n    webhook_url=os.environ['ERROR_EXPLORER_WEBHOOK_URL'],\n    project_name=os.environ['ERROR_EXPLORER_PROJECT_NAME'],\n    environment=os.environ.get('ERROR_EXPLORER_ENVIRONMENT', 'production')\n)\n```\n\n## Framework-Specific Examples\n\n### Django with Custom User Context\n\n```python\n# middleware.py\nfrom django.utils.deprecation import MiddlewareMixin\nimport error_explorer\n\nclass UserContextMiddleware(MiddlewareMixin):\n    def process_request(self, request):\n        if request.user.is_authenticated:\n            error_explorer.set_user({\n                \"id\": request.user.id,\n                \"email\": request.user.email,\n                \"username\": request.user.username,\n                \"is_staff\": request.user.is_staff\n            })\n```\n\n### Flask with Request Context\n\n```python\nfrom flask import Flask, request, g\nimport error_explorer\n\napp = Flask(__name__)\n\n@app.before_request\ndef before_request():\n    error_explorer.add_breadcrumb(\n        f\"{request.method} {request.path}\",\n        \"http\"\n    )\n    \n    if hasattr(g, 'user'):\n        error_explorer.set_user({\n            \"id\": g.user.id,\n            \"email\": g.user.email\n        })\n```\n\n## Troubleshooting\n\n### Errors not appearing in dashboard\n1. Check that the webhook URL is correct\n2. Verify that Error Explorer is running and accessible\n3. Enable debug mode: `error_explorer.init(..., debug=True)`\n4. Check the console for any Error Explorer related messages\n\n### Performance considerations\n1. Error Explorer sends data asynchronously by default\n2. Adjust `timeout` and `retries` based on your needs\n3. Use `before_send` to filter out unnecessary errors\n4. Consider rate limiting in high-traffic applications\n\n## Requirements\n\n- Python 3.7+\n- requests\n- Optional: Django 3.0+, Flask 1.0+, FastAPI 0.65.0+\n\n## License\n\nMIT\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Python SDK for Error Explorer - Capture and report errors automatically",
    "version": "1.0.1",
    "project_urls": {
        "Bug Tracker": "https://github.com/Manguet/ErrorReportPythonSDK/issues",
        "Homepage": "https://github.com/Manguet/ErrorReportPythonSDK",
        "Source": "https://github.com/Manguet/ErrorReportPythonSDK"
    },
    "split_keywords": [
        "error",
        "monitoring",
        "debugging",
        "logging",
        "django",
        "flask",
        "fastapi",
        "python"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "1e08ff6423dcdf84f219eb1b675fb27f30d082f3f2befbb3bef82bfd3a346714",
                "md5": "4ec8d328e2b1083a04bdafb796a8ea62",
                "sha256": "1b927200bd5db31559b717b69e75ba2b230ac8caf61960f0e4428528f23042a3"
            },
            "downloads": -1,
            "filename": "error-explorer-python-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "4ec8d328e2b1083a04bdafb796a8ea62",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 48273,
            "upload_time": "2025-08-12T15:53:02",
            "upload_time_iso_8601": "2025-08-12T15:53:02.064337Z",
            "url": "https://files.pythonhosted.org/packages/1e/08/ff6423dcdf84f219eb1b675fb27f30d082f3f2befbb3bef82bfd3a346714/error-explorer-python-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-12 15:53:02",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Manguet",
    "github_project": "ErrorReportPythonSDK",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "error-explorer-python"
}
        
Elapsed time: 1.29102s