or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-logging.mdindex.mdinstrumentation.mdintegrations.mdmetrics.mdspans-tracing.md

instrumentation.mddocs/

0

# Auto-Instrumentation

1

2

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.

3

4

## Capabilities

5

6

### Web Framework Instrumentation

7

8

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

9

10

```python { .api }

11

def instrument_fastapi(app, *,

12

capture_headers: bool = False,

13

request_attributes_mapper: Callable | None = None,

14

excluded_urls: str | re.Pattern | None = None,

15

record_send_receive: bool = False,

16

extra_spans: bool = False,

17

**kwargs) -> None:

18

"""

19

Instrument FastAPI application for automatic tracing.

20

21

Parameters:

22

- app: FastAPI application instance

23

- capture_headers: Whether to capture HTTP request/response headers

24

- request_attributes_mapper: Function to extract custom attributes from requests

25

- excluded_urls: URL patterns to exclude from tracing

26

- record_send_receive: Record ASGI send/receive events as spans

27

- extra_spans: Create additional spans for middleware and dependencies

28

- **kwargs: Additional OpenTelemetry instrumentation options

29

"""

30

31

def instrument_django(*,

32

capture_headers: bool = False,

33

is_sql_commentor_enabled: bool | None = None,

34

request_hook: Callable | None = None,

35

response_hook: Callable | None = None,

36

excluded_urls: str | re.Pattern | None = None,

37

**kwargs) -> None:

38

"""

39

Instrument Django application for automatic tracing.

40

41

Parameters:

42

- capture_headers: Whether to capture HTTP headers

43

- is_sql_commentor_enabled: Enable SQL query commenting with trace context

44

- request_hook: Callback for processing request spans

45

- response_hook: Callback for processing response spans

46

- excluded_urls: URL patterns to exclude from tracing

47

- **kwargs: Additional OpenTelemetry instrumentation options

48

"""

49

50

def instrument_flask(app, *,

51

capture_headers: bool = False,

52

enable_commenter: bool = True,

53

commenter_options: dict | None = None,

54

excluded_urls: str | re.Pattern | None = None,

55

request_hook: Callable | None = None,

56

response_hook: Callable | None = None,

57

**kwargs) -> None:

58

"""

59

Instrument Flask application for automatic tracing.

60

61

Parameters:

62

- app: Flask application instance

63

- capture_headers: Whether to capture HTTP headers

64

- enable_commenter: Enable SQL query commenting

65

- commenter_options: Configuration for SQL commenting

66

- excluded_urls: URL patterns to exclude from tracing

67

- request_hook: Callback for processing request spans

68

- response_hook: Callback for processing response spans

69

- **kwargs: Additional OpenTelemetry instrumentation options

70

"""

71

72

def instrument_starlette(app, *,

73

capture_headers: bool = False,

74

record_send_receive: bool = False,

75

server_request_hook: Callable | None = None,

76

client_request_hook: Callable | None = None,

77

client_response_hook: Callable | None = None,

78

**kwargs) -> None:

79

"""

80

Instrument Starlette application for automatic tracing.

81

82

Parameters:

83

- app: Starlette application instance

84

- capture_headers: Whether to capture HTTP headers

85

- record_send_receive: Record ASGI send/receive events

86

- server_request_hook: Callback for server request processing

87

- client_request_hook: Callback for client request processing

88

- client_response_hook: Callback for client response processing

89

- **kwargs: Additional OpenTelemetry instrumentation options

90

"""

91

```

92

93

**Usage Examples:**

94

95

```python

96

import logfire

97

from fastapi import FastAPI

98

from flask import Flask

99

100

# FastAPI instrumentation

101

app = FastAPI()

102

logfire.configure()

103

logfire.instrument_fastapi(app, capture_headers=True)

104

105

# Flask instrumentation

106

flask_app = Flask(__name__)

107

logfire.instrument_flask(flask_app, capture_headers=True)

108

109

# Django instrumentation (in Django settings or app startup)

110

logfire.instrument_django(capture_headers=True, is_sql_commentor_enabled=True)

111

```

112

113

### ASGI/WSGI Instrumentation

114

115

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

116

117

```python { .api }

118

def instrument_asgi(app,

119

capture_headers: bool = False,

120

record_send_receive: bool = False,

121

**kwargs) -> None:

122

"""

123

Instrument ASGI application for automatic tracing.

124

125

Parameters:

126

- app: ASGI application callable

127

- capture_headers: Whether to capture HTTP headers

128

- record_send_receive: Record ASGI send/receive events as spans

129

- **kwargs: Additional OpenTelemetry instrumentation options

130

"""

131

132

def instrument_wsgi(app,

133

capture_headers: bool = False,

134

request_hook: Callable | None = None,

135

response_hook: Callable | None = None,

136

**kwargs) -> None:

137

"""

138

Instrument WSGI application for automatic tracing.

139

140

Parameters:

141

- app: WSGI application callable

142

- capture_headers: Whether to capture HTTP headers

143

- request_hook: Callback for processing request spans

144

- response_hook: Callback for processing response spans

145

- **kwargs: Additional OpenTelemetry instrumentation options

146

"""

147

```

148

149

### AI/LLM Service Instrumentation

150

151

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

152

153

```python { .api }

154

def instrument_openai(openai_client=None, *,

155

suppress_other_instrumentation: bool = True) -> None:

156

"""

157

Instrument OpenAI client for automatic tracing of API calls.

158

159

Parameters:

160

- openai_client: Specific OpenAI client instance to instrument (None for all)

161

- suppress_other_instrumentation: Suppress other HTTP instrumentation for OpenAI calls

162

"""

163

164

def instrument_openai_agents() -> None:

165

"""

166

Instrument OpenAI Agents SDK for automatic tracing.

167

"""

168

169

def instrument_anthropic(anthropic_client=None, *,

170

suppress_other_instrumentation: bool = True) -> None:

171

"""

172

Instrument Anthropic client for automatic tracing of API calls.

173

174

Parameters:

175

- anthropic_client: Specific Anthropic client instance (None for all)

176

- suppress_other_instrumentation: Suppress other HTTP instrumentation for Anthropic calls

177

"""

178

179

def instrument_google_genai() -> None:

180

"""

181

Instrument Google Generative AI client for automatic tracing.

182

"""

183

184

def instrument_litellm(**kwargs) -> None:

185

"""

186

Instrument LiteLLM for automatic tracing of unified LLM API calls.

187

188

Parameters:

189

- **kwargs: Additional OpenTelemetry instrumentation options

190

"""

191

```

192

193

**Usage Examples:**

194

195

```python

196

import openai

197

import anthropic

198

import logfire

199

200

# OpenAI instrumentation

201

logfire.configure()

202

logfire.instrument_openai() # Instruments all OpenAI clients

203

204

# Or instrument specific client

205

client = openai.OpenAI()

206

logfire.instrument_openai(client)

207

208

# Anthropic instrumentation

209

logfire.instrument_anthropic()

210

211

# Google GenAI instrumentation

212

logfire.instrument_google_genai()

213

```

214

215

### Database Instrumentation

216

217

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

218

219

```python { .api }

220

def instrument_sqlalchemy(engine=None, *,

221

enable_commenter: bool = False,

222

commenter_options: dict | None = None,

223

**kwargs) -> None:

224

"""

225

Instrument SQLAlchemy for automatic database query tracing.

226

227

Parameters:

228

- engine: Specific SQLAlchemy engine to instrument (None for all)

229

- enable_commenter: Add trace context as SQL comments

230

- commenter_options: Configuration for SQL commenting

231

- **kwargs: Additional OpenTelemetry instrumentation options

232

"""

233

234

def instrument_asyncpg(**kwargs) -> None:

235

"""

236

Instrument asyncpg PostgreSQL driver for automatic tracing.

237

238

Parameters:

239

- **kwargs: Additional OpenTelemetry instrumentation options

240

"""

241

242

def instrument_psycopg(conn_or_module=None, *,

243

enable_commenter: bool = False,

244

commenter_options: dict | None = None,

245

**kwargs) -> None:

246

"""

247

Instrument psycopg PostgreSQL driver for automatic tracing.

248

249

Parameters:

250

- conn_or_module: Specific connection or module to instrument (None for all)

251

- enable_commenter: Add trace context as SQL comments

252

- commenter_options: Configuration for SQL commenting

253

- **kwargs: Additional OpenTelemetry instrumentation options

254

"""

255

256

def instrument_sqlite3(conn=None, **kwargs) -> None:

257

"""

258

Instrument SQLite3 for automatic database tracing.

259

260

Parameters:

261

- conn: Specific connection to instrument (None for all)

262

- **kwargs: Additional OpenTelemetry instrumentation options

263

"""

264

265

def instrument_pymongo(capture_statement: bool = False,

266

request_hook: Callable | None = None,

267

response_hook: Callable | None = None,

268

failed_hook: Callable | None = None,

269

**kwargs) -> None:

270

"""

271

Instrument PyMongo MongoDB driver for automatic tracing.

272

273

Parameters:

274

- capture_statement: Whether to capture MongoDB commands

275

- request_hook: Callback for processing request spans

276

- response_hook: Callback for processing response spans

277

- failed_hook: Callback for processing failed operations

278

- **kwargs: Additional OpenTelemetry instrumentation options

279

"""

280

281

def instrument_redis(capture_statement: bool = False,

282

request_hook: Callable | None = None,

283

response_hook: Callable | None = None,

284

**kwargs) -> None:

285

"""

286

Instrument Redis client for automatic tracing.

287

288

Parameters:

289

- capture_statement: Whether to capture Redis commands

290

- request_hook: Callback for processing request spans

291

- response_hook: Callback for processing response spans

292

- **kwargs: Additional OpenTelemetry instrumentation options

293

"""

294

295

def instrument_mysql(conn=None, **kwargs) -> None:

296

"""

297

Instrument MySQL connector for automatic tracing.

298

299

Parameters:

300

- conn: Specific connection to instrument (None for all)

301

- **kwargs: Additional OpenTelemetry instrumentation options

302

"""

303

```

304

305

**Usage Examples:**

306

307

```python

308

import sqlalchemy

309

import asyncpg

310

import pymongo

311

import logfire

312

313

logfire.configure()

314

315

# SQLAlchemy instrumentation

316

engine = sqlalchemy.create_engine('postgresql://...')

317

logfire.instrument_sqlalchemy(engine, enable_commenter=True)

318

319

# AsyncPG instrumentation

320

logfire.instrument_asyncpg()

321

322

# MongoDB instrumentation with command capturing

323

logfire.instrument_pymongo(capture_statement=True)

324

325

# Redis instrumentation

326

logfire.instrument_redis(capture_statement=True)

327

```

328

329

### HTTP Client Instrumentation

330

331

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

332

333

```python { .api }

334

def instrument_httpx(client=None, *,

335

capture_all: bool | None = None,

336

capture_headers: bool = False,

337

capture_request_body: bool = False,

338

capture_response_body: bool = False,

339

request_hook: Callable | None = None,

340

response_hook: Callable | None = None,

341

async_request_hook: Callable | None = None,

342

async_response_hook: Callable | None = None,

343

**kwargs) -> None:

344

"""

345

Instrument HTTPX client for automatic HTTP tracing.

346

347

Parameters:

348

- client: Specific HTTPX client instance (None for all)

349

- capture_all: Capture all HTTP traffic (overrides other capture settings)

350

- capture_headers: Whether to capture HTTP headers

351

- capture_request_body: Whether to capture request bodies

352

- capture_response_body: Whether to capture response bodies

353

- request_hook: Callback for processing request spans

354

- response_hook: Callback for processing response spans

355

- async_request_hook: Callback for async request processing

356

- async_response_hook: Callback for async response processing

357

- **kwargs: Additional OpenTelemetry instrumentation options

358

"""

359

360

def instrument_requests(excluded_urls: str | re.Pattern | None = None,

361

request_hook: Callable | None = None,

362

response_hook: Callable | None = None,

363

**kwargs) -> None:

364

"""

365

Instrument Requests library for automatic HTTP tracing.

366

367

Parameters:

368

- excluded_urls: URL patterns to exclude from tracing

369

- request_hook: Callback for processing request spans

370

- response_hook: Callback for processing response spans

371

- **kwargs: Additional OpenTelemetry instrumentation options

372

"""

373

374

def instrument_aiohttp_client(**kwargs) -> None:

375

"""

376

Instrument aiohttp client for automatic HTTP tracing.

377

378

Parameters:

379

- **kwargs: Additional OpenTelemetry instrumentation options

380

"""

381

382

def instrument_aiohttp_server(**kwargs) -> None:

383

"""

384

Instrument aiohttp server for automatic HTTP request tracing.

385

386

Parameters:

387

- **kwargs: Additional OpenTelemetry instrumentation options

388

"""

389

```

390

391

**Usage Examples:**

392

393

```python

394

import httpx

395

import requests

396

import logfire

397

398

logfire.configure()

399

400

# HTTPX instrumentation with body capture

401

logfire.instrument_httpx(

402

capture_headers=True,

403

capture_request_body=True,

404

capture_response_body=True

405

)

406

407

# Requests instrumentation with exclusions

408

logfire.instrument_requests(

409

excluded_urls=r'.*health.*' # Exclude health check endpoints

410

)

411

412

# aiohttp client/server

413

logfire.instrument_aiohttp_client()

414

logfire.instrument_aiohttp_server()

415

```

416

417

### Task and Message Queue Instrumentation

418

419

Instrumentation for task queues and background job processing systems.

420

421

```python { .api }

422

def instrument_celery(**kwargs) -> None:

423

"""

424

Instrument Celery for automatic task tracing.

425

426

Parameters:

427

- **kwargs: Additional OpenTelemetry instrumentation options

428

"""

429

```

430

431

### Special Purpose Instrumentation

432

433

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

434

435

```python { .api }

436

def instrument_pydantic(record: Literal['all', 'failure', 'metrics', 'off'] = 'all',

437

include: Sequence[str] = (),

438

exclude: Sequence[str] = ()) -> None:

439

"""

440

Instrument Pydantic models for validation tracking.

441

442

Parameters:

443

- record: Recording mode ('all', 'failure', 'metrics', 'off')

444

- include: Module patterns to include

445

- exclude: Module patterns to exclude

446

"""

447

448

def instrument_pydantic_ai(obj=None, /, *,

449

event_mode: Literal['attributes', 'events'] = 'attributes',

450

include_binary_content: bool | None = None,

451

**kwargs) -> None:

452

"""

453

Instrument PydanticAI for automatic AI agent tracing.

454

455

Parameters:

456

- obj: Specific object to instrument (None for all)

457

- event_mode: How to record events ('attributes' or 'events')

458

- include_binary_content: Whether to include binary content in traces

459

- **kwargs: Additional instrumentation options

460

"""

461

462

def instrument_aws_lambda(lambda_handler,

463

event_context_extractor: Callable | None = None,

464

**kwargs):

465

"""

466

Instrument AWS Lambda handler for automatic tracing.

467

468

Parameters:

469

- lambda_handler: Lambda handler function to instrument

470

- event_context_extractor: Function to extract context from events

471

- **kwargs: Additional OpenTelemetry instrumentation options

472

473

Returns: Instrumented lambda handler

474

"""

475

476

def instrument_system_metrics(config: dict | None = None,

477

base: Literal['basic', 'full'] = 'basic') -> None:

478

"""

479

Instrument system metrics collection (CPU, memory, disk, network).

480

481

Parameters:

482

- config: Custom metrics configuration

483

- base: Base metric set to collect ('basic' or 'full')

484

"""

485

486

def instrument_mcp(*, propagate_otel_context: bool = True) -> None:

487

"""

488

Instrument Model Context Protocol (MCP) for automatic tracing.

489

490

Parameters:

491

- propagate_otel_context: Whether to propagate OpenTelemetry context

492

"""

493

```

494

495

**Usage Examples:**

496

497

```python

498

import logfire

499

500

# Pydantic validation tracking

501

logfire.instrument_pydantic(record='all')

502

503

# AWS Lambda instrumentation

504

def my_lambda_handler(event, context):

505

return {'statusCode': 200}

506

507

instrumented_handler = logfire.instrument_aws_lambda(my_lambda_handler)

508

509

# System metrics collection

510

logfire.instrument_system_metrics(base='full')

511

512

# PydanticAI instrumentation

513

logfire.instrument_pydantic_ai(event_mode='events')

514

```

515

516

### Global Instrumentation Control

517

518

Utilities for managing instrumentation behavior across your application.

519

520

```python { .api }

521

def suppress_instrumentation() -> AbstractContextManager[None]:

522

"""

523

Context manager to temporarily suppress all instrumentation.

524

525

Returns: Context manager that disables instrumentation within its scope

526

"""

527

```

528

529

**Usage Example:**

530

531

```python

532

import logfire

533

534

# Some operations you don't want to trace

535

with logfire.suppress_instrumentation():

536

# This HTTP request won't be traced

537

response = requests.get('https://internal-api/health')

538

```