Metadata-Version: 2.1
Name: telescope-python
Version: 1.2.0
Summary: Python client for Telescope error monitoring
Home-page: https://github.com/us-telescope/telescope-python
License: MIT
Keywords: telescope,error-monitoring,observability,opentelemetry,logging
Author: Telescope Team
Author-email: hello@ultron.studio
Requires-Python: >=3.8,<4.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Logging
Classifier: Topic :: System :: Monitoring
Provides-Extra: all
Provides-Extra: celery
Provides-Extra: django
Provides-Extra: fastapi
Provides-Extra: flask
Requires-Dist: opentelemetry-api (>=1.20.0,<2.0.0)
Requires-Dist: opentelemetry-exporter-otlp (>=1.20.0,<2.0.0)
Requires-Dist: opentelemetry-instrumentation-celery (>=0.41b0,<0.42) ; extra == "celery" or extra == "all"
Requires-Dist: opentelemetry-instrumentation-django (>=0.41b0,<0.42) ; extra == "django" or extra == "all"
Requires-Dist: opentelemetry-instrumentation-fastapi (>=0.41b0,<0.42) ; extra == "fastapi" or extra == "all"
Requires-Dist: opentelemetry-instrumentation-flask (>=0.41b0,<0.42) ; extra == "flask" or extra == "all"
Requires-Dist: opentelemetry-instrumentation-logging (>=0.41b0,<0.42)
Requires-Dist: opentelemetry-instrumentation-psycopg2 (>=0.41b0,<0.42) ; extra == "django" or extra == "all"
Requires-Dist: opentelemetry-instrumentation-requests (>=0.41b0,<0.42)
Requires-Dist: opentelemetry-instrumentation-sqlalchemy (>=0.41b0,<0.42) ; extra == "flask" or extra == "fastapi" or extra == "all"
Requires-Dist: opentelemetry-sdk (>=1.20.0,<2.0.0)
Requires-Dist: requests (>=2.25.0,<3.0.0)
Project-URL: Documentation, https://github.com/us-telescope/telescope-python#readme
Project-URL: Repository, https://github.com/us-telescope/telescope-python
Description-Content-Type: text/markdown

# Telescope Python Client

A comprehensive Python client for Telescope error monitoring with OpenTelemetry integrations

## Features

🔹 **Error Tracking**: Automatic exception capture and reporting  
🔹 **OpenTelemetry Integration**: Full tracing and metrics support  
🔹 **Comprehensive Integrations**: 15+ framework and library integrations  
🔹 **Environment Awareness**: Production, staging, development separation  
🔹 **Performance Monitoring**: Slow query and function execution tracking  
🔹 **Context Enrichment**: Automatic user, request, and custom context  
🔹 **Auto-Discovery**: Automatic integration detection and setup  
🔹 **Sentry-like API**: Familiar patterns for Sentry users  
🔹 **Retry Logic**: Built-in retry mechanisms with telemetry  

## Installation

```bash
# Basic installation
pip install telescope-python

# With Django support
pip install telescope-python[django]

# With Flask support  
pip install telescope-python[flask]

# With FastAPI support
pip install telescope-python[fastapi]

# With all integrations
pip install telescope-python[all]
```

## 🚀 **Comprehensive Integrations**

Telescope supports **15+ major Python frameworks and libraries**:

### **Web Frameworks**
- **Django** - Full Django integration with automatic error capture
- **Flask** - Complete Flask support with request context
- **FastAPI** - Modern FastAPI integration with async support
- **Starlette** - ASGI framework integration
- **Quart** - Async Flask-compatible framework
- **Sanic** - High-performance async framework
- **Tornado** - Scalable web framework

### **Async Frameworks**
- **AioHTTP** - Async HTTP client/server framework

### **Database Integrations**
- **SQLAlchemy** - Database ORM with query tracing
- **Redis** - In-memory database with operation tracking

### **Task Queue Integrations**
- **Celery** - Distributed task queue with error tracking

### **AI/ML Integrations**
- **OpenAI** - AI API integration with request tracing

### **HTTP Client Integrations**
- **Requests** - HTTP library with error capture

### **Logging Integrations**
- **Python Logging** - Automatic log-to-error conversion

## Quick Start

### Basic Setup

```python
from telescope import TelescopeClient

# Initialize client
client = TelescopeClient(
    dsn="https://your-telescope-server.com",
    project_id="TS-123456",
    environment="production",
    api_key="your-api-key",
    enable_tracing=True,
)

# Capture an exception
try:
    risky_operation()
except Exception as e:
    client.capture_exception(e)

# Capture a message
client.capture_message("Payment processed successfully", level="info")
```

### Django Integration

```python
# settings.py
from telescope import TelescopeClient
from telescope.integrations.django import DjangoIntegration

TELESCOPE_CLIENT = TelescopeClient(
    dsn="https://your-telescope-server.com",
    project_id="TS-123456", 
    environment="production",
    api_key="your-api-key",
    enable_tracing=True,
)

# Setup Django integration
DjangoIntegration().setup(TELESCOPE_CLIENT)
```

### Flask Integration

```python
from flask import Flask
from telescope import TelescopeClient
from telescope.integrations.flask import FlaskIntegration

app = Flask(__name__)

client = TelescopeClient(
    dsn="https://your-telescope-server.com",
    project_id="TS-123456",
    environment="production",
    enable_tracing=True,
)

# Setup Flask integration
FlaskIntegration().setup(client)
```

### FastAPI Integration

```python
from fastapi import FastAPI
from telescope import TelescopeClient
from telescope.integrations.fastapi import FastAPIIntegration

app = FastAPI()

client = TelescopeClient(
    dsn="https://your-telescope-server.com",
    project_id="TS-123456",
    environment="production",
    enable_tracing=True,
)

# Setup FastAPI integration
FastAPIIntegration().setup(client)
```

### **Starlette Integration**
```python
from telescope.integrations.starlette import StarletteIntegration

# Setup Starlette integration
StarletteIntegration().setup(client)
```

### **Quart Integration**
```python
from telescope.integrations.quart import QuartIntegration

# Setup Quart integration
QuartIntegration().setup(client)
```

### **Sanic Integration**
```python
from telescope.integrations.sanic import SanicIntegration

# Setup Sanic integration
SanicIntegration().setup(client)
```

### **Tornado Integration**
```python
from telescope.integrations.tornado import TornadoIntegration

# Setup Tornado integration
TornadoIntegration().setup(client)
```

### **AioHTTP Integration**
```python
from telescope.integrations.aiohttp import AioHttpIntegration

# Setup AioHTTP integration
AioHttpIntegration().setup(client)
```

### **SQLAlchemy Integration**
```python
from telescope.integrations.sqlalchemy import SQLAlchemyIntegration

# Setup SQLAlchemy integration
SQLAlchemyIntegration().setup(client)(engine)
```

### **Redis Integration**
```python
from telescope.integrations.redis import RedisIntegration

# Setup Redis integration
RedisIntegration().setup(client)(redis_client)
```

### **Celery Integration**
```python
from telescope.integrations.celery import CeleryIntegration

# Setup Celery integration
CeleryIntegration().setup(client)(celery_app)
```

### **OpenAI Integration**
```python
from telescope.integrations.openai import OpenAIIntegration

# Setup OpenAI integration
OpenAIIntegration().setup(client)(openai_client)
```

### **Requests Integration**
```python
from telescope.integrations.requests import RequestsIntegration

# Setup Requests integration
RequestsIntegration().setup(client)()
```

### **Logging Integration**
```python
from telescope.integrations.logging import LoggingIntegration

# Setup Logging integration
LoggingIntegration().setup(client)
```

## 🔍 **Auto-Discovery System**

### **Automatic Integration Setup**
```python
from telescope import setup_integrations
from telescope.integrations import *

# Setup all available integrations automatically
integrations = [
    DjangoIntegration(),
    FlaskIntegration(),
    FastAPIIntegration(),
    SQLAlchemyIntegration(),
    RedisIntegration(),
    CeleryIntegration(),
    OpenAIIntegration(),
    RequestsIntegration(),
    LoggingIntegration(),
]

enabled_integrations = setup_integrations(
    integrations=integrations,
    with_defaults=True,
    with_auto_enabling_integrations=True,
)
```

### **Integration Registry**
```python
from telescope.integrations.registry import get_available_integrations, get_integration_info

# Get all available integrations
available = get_available_integrations()
print(available)
# ['django', 'flask', 'fastapi', 'starlette', 'quart', 'sanic', 'tornado', 'aiohttp', 'sqlalchemy', 'redis', 'celery', 'openai', 'requests', 'logging']

# Get integration info
info = get_integration_info("django")
print(info)
# {'identifier': 'django', 'min_version': (1, 8), 'auto_enabling': True}
```


# New way (preferred)
from telescope.integrations.django import DjangoIntegration
from telescope.integrations.flask import FlaskIntegration
from telescope.integrations.fastapi import FastAPIIntegration
DjangoIntegration().setup(client)
FlaskIntegration().setup(client)
FastAPIIntegration().setup(client)
```

## Advanced Usage

### Decorators

```python
from telescope import capture_errors, trace_function, performance_monitor

# Automatic error capture
@capture_errors(tags={"component": "payment"})
def process_payment(amount):
    return charge_card(amount)

# Function tracing
@trace_function(tags={"component": "database"}, capture_args=True)
def get_user(user_id):
    return User.objects.get(id=user_id)

# Performance monitoring
@performance_monitor(threshold_ms=500)
def expensive_operation():
    # Will report if takes longer than 500ms
    time.sleep(1)
```

### Context Management

```python
from telescope import set_user_context, set_tags, with_context

# Set user context
set_user_context(
    user_id="12345",
    username="john_doe", 
    email="john@example.com"
)

# Set tags
set_tags(
    component="auth",
    version="1.2.3"
)

# Temporary context
with with_context(user_id="123", component="payment"):
    # Any errors here will include this context
    process_payment()
```

### OpenTelemetry Tracing

```python
# Start a transaction
with client.start_transaction("payment_flow", op="payment") as span:
    span.set_attribute("payment.amount", 100.00)
    span.set_attribute("payment.currency", "USD")
    
    try:
        result = process_payment(100.00)
        span.set_attribute("payment.success", True)
    except Exception as e:
        span.record_exception(e)
        span.set_status(trace.Status(trace.StatusCode.ERROR))
        raise
```

### Environment-Specific Configuration

```python
import os

client = TelescopeClient(
    dsn=os.getenv("TELESCOPE_DSN"),
    project_id=os.getenv("TELESCOPE_PROJECT_ID"),
    environment=os.getenv("ENVIRONMENT", "production"),
    api_key=os.getenv("TELESCOPE_API_KEY"),
    
    # Environment-specific settings
    sample_rate=1.0 if os.getenv("ENVIRONMENT") == "production" else 0.1,
    enable_tracing=os.getenv("ENVIRONMENT") != "test",
    enable_performance=True,
)
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `dsn` | str | Required | Telescope server endpoint |
| `project_id` | str | Required | Project identifier |
| `environment` | str | "production" | Environment name |
| `api_key` | str | None | API key for authentication |
| `enable_tracing` | bool | True | Enable OpenTelemetry tracing |
| `enable_performance` | bool | True | Enable performance monitoring |
| `sample_rate` | float | 1.0 | Error sampling rate (0.0-1.0) |
| `otlp_endpoint` | str | None | OpenTelemetry collector endpoint |

## OpenTelemetry Integration

The client automatically integrates with OpenTelemetry to provide:

### Trace Correlation
- Links errors to distributed traces
- Provides trace and span IDs in error reports
- Correlates errors across service boundaries

### Automatic Instrumentation
- HTTP requests (incoming and outgoing)
- Database queries
- Framework-specific operations
- Background tasks (Celery)

### Custom Spans
```python
from opentelemetry import trace

tracer = trace.get_tracer(__name__)

with tracer.start_span("custom_operation") as span:
    span.set_attribute("operation.type", "data_processing")
    span.set_attribute("operation.batch_size", 1000)
    
    # Your code here
    process_data_batch()
```

### Metrics Collection
```python
from opentelemetry import metrics

meter = metrics.get_meter(__name__)

# Create counters and gauges
error_counter = meter.create_counter("errors_total")
response_time_histogram = meter.create_histogram("response_time_seconds")

# Record metrics
error_counter.add(1, {"error_type": "validation"})
response_time_histogram.record(0.150, {"endpoint": "/api/users"})
```

## Best Practices

### 1. Environment Configuration
```python
# Use environment variables for configuration
client = TelescopeClient(
    dsn=os.getenv("TELESCOPE_DSN"),
    project_id=os.getenv("TELESCOPE_PROJECT_ID"),
    environment=os.getenv("ENVIRONMENT", "production"),
)
```

### 2. Context Enrichment
```python
# Set context early in request lifecycle
set_user_context(user_id=request.user.id)
set_tags(
    request_id=request.headers.get("X-Request-ID"),
    feature_flags=get_active_feature_flags(request.user)
)
```

### 3. Performance Monitoring
```python
# Monitor critical paths
@performance_monitor(threshold_ms=100, tags={"critical": True})
def critical_database_query():
    return expensive_query()
```

### 4. Error Grouping
```python
# Use fingerprints for custom error grouping
client.capture_exception(
    exception,
    fingerprint=["payment", "stripe", error.code]
)
```

## Migration Guide

### From Old to New Structure

```python
# OLD (still works)
from telescope import setup_django_integration
setup_django_integration(client)

# NEW (recommended)
from telescope.integrations.django import DjangoIntegration
DjangoIntegration().setup(client)
```

### Benefits of New Structure

- ✅ **Sentry compatibility**: Familiar patterns for Sentry users
- ✅ **Better organization**: Clean, logical import structure
- ✅ **Extensibility**: Easy to add new integrations
- ✅ **Professional**: Industry-standard patterns

## Testing

```bash
# Run tests
pytest

# Test connection to Telescope server
telescope-test --dsn https://your-server.com --project-id TS-123456
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## License

MIT License - see LICENSE file for details.

