Python observability platform with structured logging, distributed tracing, metrics collection, and automatic instrumentation for popular frameworks and AI services.
npx @tessl/cli install tessl/pypi-logfire@4.3.00
# Logfire
1
2
**Pydantic Logfire** is a Python observability platform that provides comprehensive monitoring, logging, and tracing capabilities. Built on OpenTelemetry standards, Logfire offers powerful observability tools with a focus on Python-centric insights, simple integration, and SQL-based querying of telemetry data.
3
4
## Package Information
5
6
- **Package Name**: logfire
7
- **Language**: Python
8
- **Installation**: `pip install logfire`
9
- **Authentication**: `logfire auth` (CLI command)
10
11
## Core Imports
12
13
```python
14
import logfire
15
```
16
17
For type annotations:
18
19
```python
20
from logfire import Logfire, LogfireSpan, ConsoleOptions, LevelName, AutoTraceModule
21
```
22
23
## Basic Usage
24
25
```python
26
import logfire
27
from datetime import date
28
29
# Configure logfire (call once at application startup)
30
logfire.configure()
31
32
# Basic logging
33
logfire.info('Hello, {name}!', name='world')
34
logfire.error('Something went wrong: {error}', error='connection failed')
35
36
# Structured logging with attributes
37
logfire.info('User login', user_id=123, ip_address='192.168.1.1', success=True)
38
39
# Span creation for tracking operations
40
with logfire.span('Processing user {user_id}', user_id=123):
41
logfire.debug('Starting validation')
42
# ... processing logic
43
logfire.info('Processing complete')
44
45
# Function instrumentation
46
@logfire.instrument
47
def calculate_total(items):
48
return sum(item.price for item in items)
49
```
50
51
## Architecture
52
53
Logfire is built on the OpenTelemetry standard and provides three core observability signals:
54
55
- **Logs**: Structured event records with levels (trace, debug, info, notice, warning, error, fatal)
56
- **Traces**: Distributed request tracking through spans that form hierarchical execution trees
57
- **Metrics**: Quantitative measurements (counters, histograms, gauges) for performance monitoring
58
59
The architecture enables:
60
- **Distributed Tracing**: Track requests across services and systems
61
- **Structured Logging**: Rich context with attributes and hierarchical organization
62
- **Performance Monitoring**: Built-in metrics collection and custom metric creation
63
- **Integration Ecosystem**: Automatic instrumentation for popular Python frameworks and libraries
64
65
## Capabilities
66
67
### Core Logging Methods
68
69
Essential logging functionality providing structured event recording with multiple severity levels, exception tracking, and rich context through attributes and tags.
70
71
```python { .api }
72
def trace(msg_template, /, *, _tags=None, _exc_info=False, **attributes): ...
73
def debug(msg_template, /, *, _tags=None, _exc_info=False, **attributes): ...
74
def info(msg_template, /, *, _tags=None, _exc_info=False, **attributes): ...
75
def notice(msg_template, /, *, _tags=None, _exc_info=False, **attributes): ...
76
def warning(msg_template, /, *, _tags=None, _exc_info=False, **attributes): ...
77
def error(msg_template, /, *, _tags=None, _exc_info=False, **attributes): ...
78
def fatal(msg_template, /, *, _tags=None, _exc_info=False, **attributes): ...
79
def exception(msg_template, /, *, _tags=None, _exc_info=True, **attributes): ...
80
81
def log(level: LevelName | int, msg_template: str, attributes: dict[str, Any] | None = None,
82
tags: Sequence[str] | None = None, exc_info: bool = False, console_log: bool | None = None): ...
83
84
def configure(*, send_to_logfire: bool | Literal['if-token-present'] | None = None,
85
token: str | None = None, service_name: str | None = None,
86
console: ConsoleOptions | False | None = None, **kwargs) -> Logfire: ...
87
```
88
89
[Core Logging](./core-logging.md)
90
91
### Auto-Instrumentation
92
93
Comprehensive automatic instrumentation for popular Python frameworks, libraries, and services, enabling zero-configuration observability for web applications, databases, AI services, and more.
94
95
```python { .api }
96
# Web Frameworks
97
def instrument_fastapi(app, *, capture_headers: bool = False, **kwargs): ...
98
def instrument_django(*, capture_headers: bool = False, **kwargs): ...
99
def instrument_flask(app, *, capture_headers: bool = False, **kwargs): ...
100
def instrument_starlette(app, *, capture_headers: bool = False, **kwargs): ...
101
102
# AI/LLM Services
103
def instrument_openai(openai_client=None, *, suppress_other_instrumentation: bool = True): ...
104
def instrument_anthropic(anthropic_client=None, *, suppress_other_instrumentation: bool = True): ...
105
106
# Databases
107
def instrument_sqlalchemy(engine=None, *, enable_commenter: bool = False, **kwargs): ...
108
def instrument_asyncpg(**kwargs): ...
109
def instrument_redis(*, capture_statement: bool = False, **kwargs): ...
110
111
# HTTP Clients
112
def instrument_httpx(client=None, *, capture_headers: bool = False, **kwargs): ...
113
def instrument_requests(*, excluded_urls=None, **kwargs): ...
114
```
115
116
[Instrumentation](./instrumentation.md)
117
118
### Spans and Tracing
119
120
Manual span creation and management for tracking operations, creating distributed traces, and organizing observability data hierarchically with full OpenTelemetry compatibility.
121
122
```python { .api }
123
def span(msg_template: str, /, *, _tags: Sequence[str] | None = None,
124
_span_name: str | None = None, _level: LevelName | int | None = None,
125
_links: Sequence = (), **attributes) -> LogfireSpan: ...
126
127
def instrument(msg_template: str | None = None, *, span_name: str | None = None,
128
extract_args: bool = True, record_return: bool = False,
129
allow_generator: bool = False): ...
130
131
def install_auto_tracing(modules: Sequence[str] | Callable[[AutoTraceModule], bool], *,
132
min_duration: float,
133
check_imported_modules: Literal['error', 'warn', 'ignore'] = 'error'): ...
134
135
class LogfireSpan:
136
def set_attribute(self, key: str, value: Any) -> None: ...
137
def set_attributes(self, attributes: dict[str, Any]) -> None: ...
138
def record_exception(self, exception: BaseException, *, attributes: dict[str, Any] | None = None,
139
timestamp: int | None = None, escaped: bool = False) -> None: ...
140
```
141
142
[Spans and Tracing](./spans-tracing.md)
143
144
### Metrics
145
146
Metrics creation and management for quantitative monitoring including counters, histograms, gauges, and callback-based metrics with OpenTelemetry compatibility.
147
148
```python { .api }
149
def metric_counter(name: str, *, unit: str = '', description: str = '') -> Counter: ...
150
def metric_histogram(name: str, *, unit: str = '', description: str = '') -> Histogram: ...
151
def metric_gauge(name: str, *, unit: str = '', description: str = '') -> Gauge: ...
152
def metric_up_down_counter(name: str, *, unit: str = '', description: str = '') -> UpDownCounter: ...
153
154
def metric_counter_callback(name: str, *, callbacks: Sequence[Callable],
155
unit: str = '', description: str = ''): ...
156
def metric_gauge_callback(name: str, callbacks: Sequence[Callable],
157
*, unit: str = '', description: str = ''): ...
158
```
159
160
[Metrics](./metrics.md)
161
162
### Integrations and Handlers
163
164
Integration components for connecting Logfire with standard logging frameworks, structured logging libraries, and external systems.
165
166
```python { .api }
167
class LogfireLoggingHandler:
168
"""Handler for Python standard library logging integration."""
169
def __init__(self, logfire: Logfire | None = None): ...
170
171
class StructlogProcessor:
172
"""Processor for structlog integration (alias: LogfireProcessor)."""
173
def __init__(self, logfire: Logfire | None = None): ...
174
175
def loguru_handler() -> dict[str, Any]:
176
"""Create a Logfire handler for Loguru integration."""
177
178
def suppress_instrumentation() -> AbstractContextManager[None]: ...
179
def get_baggage() -> dict[str, str]: ...
180
def set_baggage(baggage: dict[str, str]) -> Token: ...
181
182
# Version information
183
__version__: str # Package version string (e.g., "4.3.6")
184
```
185
186
[Integrations](./integrations.md)