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

core-logging.mddocs/

Core Logging Methods

Essential logging functionality providing structured event recording with multiple severity levels, exception tracking, and rich context through attributes and tags. These methods form the foundation of Logfire's observability capabilities.

Capabilities

Log Level Methods

Standard logging methods that record events at different severity levels. All methods support message templating with attributes, tag assignment, and exception information capture.

def trace(msg_template: str, /, *, _tags: Sequence[str] | None = None, 
          _exc_info: bool = False, **attributes) -> None:
    """
    Log a trace level message for detailed debugging information.
    
    Parameters:
    - msg_template: Message template with {} placeholders for attributes
    - _tags: Optional sequence of tags to apply to this log entry
    - _exc_info: Whether to capture current exception information
    - **attributes: Key-value pairs for structured data and template substitution
    """

def debug(msg_template: str, /, *, _tags: Sequence[str] | None = None,
          _exc_info: bool = False, **attributes) -> None:
    """
    Log a debug level message for diagnostic information.
    
    Parameters: Same as trace()
    """

def info(msg_template: str, /, *, _tags: Sequence[str] | None = None,
         _exc_info: bool = False, **attributes) -> None:
    """
    Log an info level message for general information.
    
    Parameters: Same as trace()
    """

def notice(msg_template: str, /, *, _tags: Sequence[str] | None = None,
           _exc_info: bool = False, **attributes) -> None:
    """
    Log a notice level message for significant but normal events.
    
    Parameters: Same as trace()
    """

def warning(msg_template: str, /, *, _tags: Sequence[str] | None = None,
            _exc_info: bool = False, **attributes) -> None:
    """
    Log a warning level message for potentially harmful situations.
    
    Parameters: Same as trace()
    """

# Alias for warning
warn = warning

def error(msg_template: str, /, *, _tags: Sequence[str] | None = None,
          _exc_info: bool = False, **attributes) -> None:
    """
    Log an error level message for error events that don't stop execution.
    
    Parameters: Same as trace()
    """

def fatal(msg_template: str, /, *, _tags: Sequence[str] | None = None,
          _exc_info: bool = False, **attributes) -> None:
    """
    Log a fatal level message for very severe error events.
    
    Parameters: Same as trace()
    """

def exception(msg_template: str, /, *, _tags: Sequence[str] | None = None,
              _exc_info: bool = True, **attributes) -> None:
    """
    Log an exception with traceback information (error level with exc_info=True by default).
    
    Parameters: Same as trace(), but _exc_info defaults to True
    """

Usage Examples:

import logfire

# Basic logging
logfire.info('User logged in')
logfire.error('Database connection failed')

# Message templating
logfire.info('User {user_id} performed {action}', user_id=123, action='login')

# With tags
logfire.warning('Rate limit exceeded', _tags=['security', 'rate-limiting'], 
                user_id=456, attempts=10)

# Exception logging
try:
    result = 1 / 0
except ZeroDivisionError:
    logfire.exception('Division by zero error', operation='calculate')

Generic Log Method

Flexible logging method that allows dynamic level specification and comprehensive parameter control.

def log(level: LevelName | int, msg_template: str, 
        attributes: dict[str, Any] | None = None,
        tags: Sequence[str] | None = None, 
        exc_info: bool = False,
        console_log: bool | None = None) -> None:
    """
    Generic log method with full parameter control.
    
    Parameters:
    - level: Log level name ('trace', 'debug', 'info', 'notice', 'warning', 'error', 'fatal') or integer
    - msg_template: Message template string
    - attributes: Dictionary of attributes for structured data
    - tags: Sequence of tags to apply
    - exc_info: Whether to capture exception information
    - console_log: Override console logging setting for this message
    """

Usage Example:

# Dynamic level logging
log_level = 'error' if has_error else 'info'
logfire.log(log_level, 'Operation completed', 
           attributes={'duration': 1.5, 'success': not has_error})

Configuration

Main configuration function for setting up Logfire with comprehensive options for service identification, output destinations, and observability features.

def configure(*, 
              send_to_logfire: bool | Literal['if-token-present'] | None = None,
              token: str | None = None,
              service_name: str | None = None,
              service_version: str | None = None,
              environment: str | None = None,
              console: ConsoleOptions | False | None = None,
              config_dir: Path | str | None = None,
              data_dir: Path | str | None = None,
              min_level: int | LevelName | None = None,
              sampling: SamplingOptions | None = None,
              scrubbing: ScrubbingOptions | False | None = None,
              inspect_arguments: bool | None = None,
              metrics: MetricsOptions | False | None = None,
              code_source: CodeSource | None = None,
              distributed_tracing: bool | None = None,
              advanced: AdvancedOptions | None = None,
              additional_span_processors: Sequence[SpanProcessor] | None = None,
              add_baggage_to_attributes: bool = True,
              local: bool = False) -> Logfire:
    """
    Configure Logfire with comprehensive options.
    
    Parameters:
    - send_to_logfire: Whether to send data to logfire.dev ('if-token-present', True, False)
    - token: Project token for logfire.dev
    - service_name: Name of your service/application
    - service_version: Version of your service
    - environment: Environment name (dev, staging, prod, etc.)
    - console: Console output configuration or False to disable
    - config_dir: Directory for configuration files
    - data_dir: Directory for local data storage
    - min_level: Minimum log level to record
    - sampling: Sampling configuration for traces
    - scrubbing: Data scrubbing/redaction configuration
    - inspect_arguments: Enable f-string magic for automatic attribute extraction
    - metrics: Metrics collection configuration
    - code_source: Source code location configuration
    - distributed_tracing: Enable distributed tracing headers
    - advanced: Advanced configuration options
    - additional_span_processors: Custom OpenTelemetry span processors
    - add_baggage_to_attributes: Add OpenTelemetry baggage as span attributes
    - local: Create local instance instead of configuring global instance
    
    Returns: Configured Logfire instance
    """

Usage Examples:

# Basic configuration
logfire.configure()

# Production configuration
logfire.configure(
    service_name='my-web-app',
    service_version='1.2.0', 
    environment='production',
    send_to_logfire=True,
    min_level='info'
)

# Development configuration with custom console options
logfire.configure(
    service_name='my-web-app',
    environment='development',
    console=logfire.ConsoleOptions(
        colors='always',
        include_timestamps=True,
        verbose=True
    ),
    send_to_logfire='if-token-present'
)

Configuration Classes

Supporting configuration classes for customizing Logfire behavior.

class ConsoleOptions:
    """Configuration for console output formatting and display."""
    colors: Literal['auto', 'always', 'never'] = 'auto'
    span_style: Literal['simple', 'indented', 'show-parents'] = 'simple' 
    include_timestamps: bool = True
    include_tags: bool = True
    verbose: bool = False
    min_log_level: LevelName = 'trace'
    show_project_link: bool = True

class ScrubbingOptions:
    """Configuration for data scrubbing and redaction."""
    callback: ScrubCallback | None = None
    extra_patterns: Sequence[str] | None = None

class MetricsOptions:
    """Configuration for metrics collection."""
    additional_readers: Sequence[MetricReader] = ()
    collect_in_spans: bool = True

class CodeSource:
    """Source code location configuration."""
    repository: str
    revision: str
    root_path: str

class AdvancedOptions:
    """Advanced configuration options."""
    base_url: str | None = None
    id_generator: IdGenerator = RandomIdGenerator()
    ns_timestamp_generator: Callable[[], int] = time.time_ns
    log_record_processors: Sequence[LogRecordProcessor] = ()
    
    def generate_base_url(self, token: str) -> str: ...

Type Definitions

# Log level names
LevelName = Literal['trace', 'debug', 'info', 'notice', 'warn', 'warning', 'error', 'fatal']

# Scrubbing callback signature  
ScrubCallback = Callable[[ScrubMatch], str]

class ScrubMatch:
    """Information about a potential scrubbing match."""
    path: JsonPath
    value: Any 
    pattern_match: re.Match[str]

# Sampling configuration
class SamplingOptions:
    """Configuration for trace sampling behavior."""
    # Implementation details vary based on sampling strategy

Instance Management

Methods for creating customized Logfire instances and managing settings.

def with_tags(*tags: str) -> Logfire:
    """
    Create a new Logfire instance with additional tags applied to all operations.
    
    Parameters:
    - *tags: Tags to add to the new instance
    
    Returns: New Logfire instance with additional tags
    """

def with_settings(*, 
                  tags: Sequence[str] = (),
                  stack_offset: int | None = None,
                  console_log: bool | None = None,
                  custom_scope_suffix: str | None = None) -> Logfire:
    """
    Create a new Logfire instance with custom settings.
    
    Parameters:
    - tags: Additional tags to apply
    - stack_offset: Stack level offset for source location tracking
    - console_log: Console output override
    - custom_scope_suffix: Custom suffix for OpenTelemetry scope
    
    Returns: New Logfire instance with custom settings
    """

Usage Examples:

# Tagged logger instances
auth_logger = logfire.with_tags('auth', 'security')
db_logger = logfire.with_tags('database', 'persistence')

auth_logger.info('User login attempt', user_id=123)  # Includes auth, security tags
db_logger.error('Query timeout', query='SELECT * FROM users')  # Includes database, persistence tags

# Custom settings
verbose_logger = logfire.with_settings(
    console_log=True,
    tags=['verbose']
)

Lifecycle Management

Methods for controlling Logfire's runtime behavior and resource cleanup.

def force_flush(timeout_millis: int = 3000) -> bool:
    """
    Force flush all pending spans and metrics to configured exporters.
    
    Parameters:
    - timeout_millis: Maximum time to wait for flush completion
    
    Returns: True if flush completed within timeout, False otherwise
    """

def shutdown(timeout_millis: int = 30000, flush: bool = True) -> bool:
    """
    Shutdown all tracers and meters, optionally flushing pending data.
    
    Parameters:
    - timeout_millis: Maximum time to wait for shutdown completion  
    - flush: Whether to flush pending data before shutdown
    
    Returns: True if shutdown completed within timeout, False otherwise
    """

Usage Examples:

# Ensure data is sent before application exit
logfire.force_flush()

# Clean shutdown at application termination
logfire.shutdown(flush=True, timeout_millis=5000)

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