Skip to main content

Python client for Telescope error monitoring

Project description

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

# 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

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

# 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

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

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

from telescope.integrations.starlette import StarletteIntegration

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

Quart Integration

from telescope.integrations.quart import QuartIntegration

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

Sanic Integration

from telescope.integrations.sanic import SanicIntegration

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

Tornado Integration

from telescope.integrations.tornado import TornadoIntegration

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

AioHTTP Integration

from telescope.integrations.aiohttp import AioHttpIntegration

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

SQLAlchemy Integration

from telescope.integrations.sqlalchemy import SQLAlchemyIntegration

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

Redis Integration

from telescope.integrations.redis import RedisIntegration

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

Celery Integration

from telescope.integrations.celery import CeleryIntegration

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

OpenAI Integration

from telescope.integrations.openai import OpenAIIntegration

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

Requests Integration

from telescope.integrations.requests import RequestsIntegration

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

Logging Integration

from telescope.integrations.logging import LoggingIntegration

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

🔍 Auto-Discovery System

Automatic Integration Setup

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

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

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

# 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

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

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

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

# 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

# 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

# Monitor critical paths
@performance_monitor(threshold_ms=100, tags={"critical": True})
def critical_database_query():
    return expensive_query()

4. Error Grouping

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

Migration Guide

From Old to New Structure

# 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

# 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

telescope_python-1.2.2.tar.gz (27.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

telescope_python-1.2.2-py3-none-any.whl (36.0 kB view details)

Uploaded Python 3

File details

Details for the file telescope_python-1.2.2.tar.gz.

File metadata

  • Download URL: telescope_python-1.2.2.tar.gz
  • Upload date:
  • Size: 27.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.13.5 Darwin/24.6.0

File hashes

Hashes for telescope_python-1.2.2.tar.gz
Algorithm Hash digest
SHA256 0c40f2eef8f9986d7227a5d3f0d8b13fbcfc17429e31d556bc9da06418482804
MD5 189ee4e199b25f96c1ef168151eb13ef
BLAKE2b-256 576284219a064ca417cb3ca4ae1192756f716453ceff8c446ea4fa84b3f1d976

See more details on using hashes here.

File details

Details for the file telescope_python-1.2.2-py3-none-any.whl.

File metadata

  • Download URL: telescope_python-1.2.2-py3-none-any.whl
  • Upload date:
  • Size: 36.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.13.5 Darwin/24.6.0

File hashes

Hashes for telescope_python-1.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0412ef118cbbd40c77e45ddf31db63ef8c37787b8bf47647bb11416a91d0f4c6
MD5 a1d3d67735c4f4eab48b6605f26a7462
BLAKE2b-256 16ce83a9dd31455f897b84f76eac42096bcb099c767e6bf716a92987d20bcdbc

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page