CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-logfire

Python observability platform with structured logging, distributed tracing, metrics collection, and automatic instrumentation for popular frameworks and AI services.

Pending
Overview
Eval results
Files

instrumentation.mddocs/

Auto-Instrumentation

Comprehensive automatic instrumentation for popular Python frameworks, libraries, and services, enabling zero-configuration observability. Logfire provides ready-to-use instrumentation for web frameworks, databases, AI services, HTTP clients, and more.

Capabilities

Web Framework Instrumentation

Automatic instrumentation for popular Python web frameworks, capturing HTTP requests, responses, routing information, and performance metrics.

def instrument_fastapi(app, *, 
                      capture_headers: bool = False,
                      request_attributes_mapper: Callable | None = None,
                      excluded_urls: str | re.Pattern | None = None,
                      record_send_receive: bool = False,
                      extra_spans: bool = False,
                      **kwargs) -> None:
    """
    Instrument FastAPI application for automatic tracing.
    
    Parameters:
    - app: FastAPI application instance
    - capture_headers: Whether to capture HTTP request/response headers
    - request_attributes_mapper: Function to extract custom attributes from requests
    - excluded_urls: URL patterns to exclude from tracing
    - record_send_receive: Record ASGI send/receive events as spans
    - extra_spans: Create additional spans for middleware and dependencies
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_django(*, 
                     capture_headers: bool = False,
                     is_sql_commentor_enabled: bool | None = None,
                     request_hook: Callable | None = None,
                     response_hook: Callable | None = None,
                     excluded_urls: str | re.Pattern | None = None,
                     **kwargs) -> None:
    """
    Instrument Django application for automatic tracing.
    
    Parameters:
    - capture_headers: Whether to capture HTTP headers
    - is_sql_commentor_enabled: Enable SQL query commenting with trace context
    - request_hook: Callback for processing request spans
    - response_hook: Callback for processing response spans
    - excluded_urls: URL patterns to exclude from tracing
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_flask(app, *,
                    capture_headers: bool = False,
                    enable_commenter: bool = True,
                    commenter_options: dict | None = None,
                    excluded_urls: str | re.Pattern | None = None,
                    request_hook: Callable | None = None,
                    response_hook: Callable | None = None,
                    **kwargs) -> None:
    """
    Instrument Flask application for automatic tracing.
    
    Parameters:
    - app: Flask application instance
    - capture_headers: Whether to capture HTTP headers
    - enable_commenter: Enable SQL query commenting
    - commenter_options: Configuration for SQL commenting
    - excluded_urls: URL patterns to exclude from tracing
    - request_hook: Callback for processing request spans
    - response_hook: Callback for processing response spans
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_starlette(app, *,
                        capture_headers: bool = False,
                        record_send_receive: bool = False,
                        server_request_hook: Callable | None = None,
                        client_request_hook: Callable | None = None,
                        client_response_hook: Callable | None = None,
                        **kwargs) -> None:
    """
    Instrument Starlette application for automatic tracing.
    
    Parameters:
    - app: Starlette application instance
    - capture_headers: Whether to capture HTTP headers
    - record_send_receive: Record ASGI send/receive events
    - server_request_hook: Callback for server request processing
    - client_request_hook: Callback for client request processing
    - client_response_hook: Callback for client response processing
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

Usage Examples:

import logfire
from fastapi import FastAPI
from flask import Flask

# FastAPI instrumentation
app = FastAPI()
logfire.configure()
logfire.instrument_fastapi(app, capture_headers=True)

# Flask instrumentation  
flask_app = Flask(__name__)
logfire.instrument_flask(flask_app, capture_headers=True)

# Django instrumentation (in Django settings or app startup)
logfire.instrument_django(capture_headers=True, is_sql_commentor_enabled=True)

ASGI/WSGI Instrumentation

Lower-level instrumentation for ASGI and WSGI applications, providing flexibility for custom frameworks or direct server integration.

def instrument_asgi(app,
                   capture_headers: bool = False,
                   record_send_receive: bool = False,
                   **kwargs) -> None:
    """
    Instrument ASGI application for automatic tracing.
    
    Parameters:
    - app: ASGI application callable
    - capture_headers: Whether to capture HTTP headers
    - record_send_receive: Record ASGI send/receive events as spans
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_wsgi(app,
                   capture_headers: bool = False,
                   request_hook: Callable | None = None,
                   response_hook: Callable | None = None,
                   **kwargs) -> None:
    """
    Instrument WSGI application for automatic tracing.
    
    Parameters:
    - app: WSGI application callable
    - capture_headers: Whether to capture HTTP headers  
    - request_hook: Callback for processing request spans
    - response_hook: Callback for processing response spans
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

AI/LLM Service Instrumentation

Specialized instrumentation for AI and Large Language Model services, capturing API calls, token usage, and model interactions.

def instrument_openai(openai_client=None, *,
                     suppress_other_instrumentation: bool = True) -> None:
    """
    Instrument OpenAI client for automatic tracing of API calls.
    
    Parameters:
    - openai_client: Specific OpenAI client instance to instrument (None for all)
    - suppress_other_instrumentation: Suppress other HTTP instrumentation for OpenAI calls
    """

def instrument_openai_agents() -> None:
    """
    Instrument OpenAI Agents SDK for automatic tracing.
    """

def instrument_anthropic(anthropic_client=None, *,
                        suppress_other_instrumentation: bool = True) -> None:
    """
    Instrument Anthropic client for automatic tracing of API calls.
    
    Parameters:
    - anthropic_client: Specific Anthropic client instance (None for all)
    - suppress_other_instrumentation: Suppress other HTTP instrumentation for Anthropic calls
    """

def instrument_google_genai() -> None:
    """
    Instrument Google Generative AI client for automatic tracing.
    """

def instrument_litellm(**kwargs) -> None:
    """
    Instrument LiteLLM for automatic tracing of unified LLM API calls.
    
    Parameters:
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

Usage Examples:

import openai
import anthropic
import logfire

# OpenAI instrumentation
logfire.configure()
logfire.instrument_openai()  # Instruments all OpenAI clients

# Or instrument specific client
client = openai.OpenAI()
logfire.instrument_openai(client)

# Anthropic instrumentation
logfire.instrument_anthropic()

# Google GenAI instrumentation  
logfire.instrument_google_genai()

Database Instrumentation

Comprehensive database instrumentation covering SQL databases, NoSQL systems, and ORMs with query capturing and performance tracking.

def instrument_sqlalchemy(engine=None, *,
                         enable_commenter: bool = False,
                         commenter_options: dict | None = None,
                         **kwargs) -> None:
    """
    Instrument SQLAlchemy for automatic database query tracing.
    
    Parameters:
    - engine: Specific SQLAlchemy engine to instrument (None for all)
    - enable_commenter: Add trace context as SQL comments
    - commenter_options: Configuration for SQL commenting
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_asyncpg(**kwargs) -> None:
    """
    Instrument asyncpg PostgreSQL driver for automatic tracing.
    
    Parameters:
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_psycopg(conn_or_module=None, *,
                      enable_commenter: bool = False,
                      commenter_options: dict | None = None,
                      **kwargs) -> None:
    """
    Instrument psycopg PostgreSQL driver for automatic tracing.
    
    Parameters:
    - conn_or_module: Specific connection or module to instrument (None for all)
    - enable_commenter: Add trace context as SQL comments
    - commenter_options: Configuration for SQL commenting
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_sqlite3(conn=None, **kwargs) -> None:
    """
    Instrument SQLite3 for automatic database tracing.
    
    Parameters:
    - conn: Specific connection to instrument (None for all)
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_pymongo(capture_statement: bool = False,
                      request_hook: Callable | None = None,
                      response_hook: Callable | None = None,
                      failed_hook: Callable | None = None,
                      **kwargs) -> None:
    """
    Instrument PyMongo MongoDB driver for automatic tracing.
    
    Parameters:
    - capture_statement: Whether to capture MongoDB commands
    - request_hook: Callback for processing request spans
    - response_hook: Callback for processing response spans  
    - failed_hook: Callback for processing failed operations
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_redis(capture_statement: bool = False,
                    request_hook: Callable | None = None,
                    response_hook: Callable | None = None,
                    **kwargs) -> None:
    """
    Instrument Redis client for automatic tracing.
    
    Parameters:
    - capture_statement: Whether to capture Redis commands
    - request_hook: Callback for processing request spans
    - response_hook: Callback for processing response spans
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_mysql(conn=None, **kwargs) -> None:
    """
    Instrument MySQL connector for automatic tracing.
    
    Parameters:
    - conn: Specific connection to instrument (None for all)
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

Usage Examples:

import sqlalchemy
import asyncpg
import pymongo
import logfire

logfire.configure()

# SQLAlchemy instrumentation
engine = sqlalchemy.create_engine('postgresql://...')
logfire.instrument_sqlalchemy(engine, enable_commenter=True)

# AsyncPG instrumentation
logfire.instrument_asyncpg()

# MongoDB instrumentation with command capturing
logfire.instrument_pymongo(capture_statement=True)

# Redis instrumentation
logfire.instrument_redis(capture_statement=True)

HTTP Client Instrumentation

Automatic instrumentation for HTTP clients, capturing outbound requests, responses, and network performance metrics.

def instrument_httpx(client=None, *,
                    capture_all: bool | None = None,
                    capture_headers: bool = False,
                    capture_request_body: bool = False,
                    capture_response_body: bool = False,
                    request_hook: Callable | None = None,
                    response_hook: Callable | None = None,
                    async_request_hook: Callable | None = None,
                    async_response_hook: Callable | None = None,
                    **kwargs) -> None:
    """
    Instrument HTTPX client for automatic HTTP tracing.
    
    Parameters:
    - client: Specific HTTPX client instance (None for all)
    - capture_all: Capture all HTTP traffic (overrides other capture settings)
    - capture_headers: Whether to capture HTTP headers
    - capture_request_body: Whether to capture request bodies
    - capture_response_body: Whether to capture response bodies
    - request_hook: Callback for processing request spans
    - response_hook: Callback for processing response spans
    - async_request_hook: Callback for async request processing
    - async_response_hook: Callback for async response processing
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_requests(excluded_urls: str | re.Pattern | None = None,
                       request_hook: Callable | None = None,
                       response_hook: Callable | None = None,
                       **kwargs) -> None:
    """
    Instrument Requests library for automatic HTTP tracing.
    
    Parameters:
    - excluded_urls: URL patterns to exclude from tracing
    - request_hook: Callback for processing request spans
    - response_hook: Callback for processing response spans
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_aiohttp_client(**kwargs) -> None:
    """
    Instrument aiohttp client for automatic HTTP tracing.
    
    Parameters:
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

def instrument_aiohttp_server(**kwargs) -> None:
    """
    Instrument aiohttp server for automatic HTTP request tracing.
    
    Parameters:
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

Usage Examples:

import httpx
import requests
import logfire

logfire.configure()

# HTTPX instrumentation with body capture
logfire.instrument_httpx(
    capture_headers=True,
    capture_request_body=True,
    capture_response_body=True
)

# Requests instrumentation with exclusions
logfire.instrument_requests(
    excluded_urls=r'.*health.*'  # Exclude health check endpoints
)

# aiohttp client/server
logfire.instrument_aiohttp_client()
logfire.instrument_aiohttp_server()

Task and Message Queue Instrumentation

Instrumentation for task queues and background job processing systems.

def instrument_celery(**kwargs) -> None:
    """
    Instrument Celery for automatic task tracing.
    
    Parameters:
    - **kwargs: Additional OpenTelemetry instrumentation options
    """

Special Purpose Instrumentation

Specialized instrumentation for specific use cases including data validation, serverless functions, and system monitoring.

def instrument_pydantic(record: Literal['all', 'failure', 'metrics', 'off'] = 'all',
                       include: Sequence[str] = (),
                       exclude: Sequence[str] = ()) -> None:
    """
    Instrument Pydantic models for validation tracking.
    
    Parameters:
    - record: Recording mode ('all', 'failure', 'metrics', 'off')
    - include: Module patterns to include
    - exclude: Module patterns to exclude
    """

def instrument_pydantic_ai(obj=None, /, *,
                          event_mode: Literal['attributes', 'events'] = 'attributes',
                          include_binary_content: bool | None = None,
                          **kwargs) -> None:
    """
    Instrument PydanticAI for automatic AI agent tracing.
    
    Parameters:
    - obj: Specific object to instrument (None for all)
    - event_mode: How to record events ('attributes' or 'events')
    - include_binary_content: Whether to include binary content in traces
    - **kwargs: Additional instrumentation options
    """

def instrument_aws_lambda(lambda_handler,
                         event_context_extractor: Callable | None = None,
                         **kwargs):
    """
    Instrument AWS Lambda handler for automatic tracing.
    
    Parameters:
    - lambda_handler: Lambda handler function to instrument
    - event_context_extractor: Function to extract context from events
    - **kwargs: Additional OpenTelemetry instrumentation options
    
    Returns: Instrumented lambda handler
    """

def instrument_system_metrics(config: dict | None = None,
                             base: Literal['basic', 'full'] = 'basic') -> None:
    """
    Instrument system metrics collection (CPU, memory, disk, network).
    
    Parameters:
    - config: Custom metrics configuration
    - base: Base metric set to collect ('basic' or 'full')
    """

def instrument_mcp(*, propagate_otel_context: bool = True) -> None:
    """
    Instrument Model Context Protocol (MCP) for automatic tracing.
    
    Parameters:
    - propagate_otel_context: Whether to propagate OpenTelemetry context
    """

Usage Examples:

import logfire

# Pydantic validation tracking
logfire.instrument_pydantic(record='all')

# AWS Lambda instrumentation
def my_lambda_handler(event, context):
    return {'statusCode': 200}

instrumented_handler = logfire.instrument_aws_lambda(my_lambda_handler)

# System metrics collection
logfire.instrument_system_metrics(base='full')

# PydanticAI instrumentation
logfire.instrument_pydantic_ai(event_mode='events')

Global Instrumentation Control

Utilities for managing instrumentation behavior across your application.

def suppress_instrumentation() -> AbstractContextManager[None]:
    """
    Context manager to temporarily suppress all instrumentation.
    
    Returns: Context manager that disables instrumentation within its scope
    """

Usage Example:

import logfire

# Some operations you don't want to trace
with logfire.suppress_instrumentation():
    # This HTTP request won't be traced
    response = requests.get('https://internal-api/health')

Install with Tessl CLI

npx tessl i tessl/pypi-logfire

docs

core-logging.md

index.md

instrumentation.md

integrations.md

metrics.md

spans-tracing.md

tile.json