Skip to content

SQLAlchemy

See every database query your app runs through SQLAlchemy in Logfire: the SQL statement, how long it took, and which ones failed. Each query becomes a span (one timed step, with a name and a duration), shown nested inside the request that triggered it, so you can spot the slow or failing query behind a slow endpoint.

What you’ll capture

  • One span per query, with its duration and status
  • The SQL statement that ran, and the database it ran against
  • Failed queries, with the error

Before you start

You’ll need a Logfire project. Open Add data in your project (top navigation) and follow the setup for your language: it signs your machine in with logfire auth (a browser sign-in, no token to copy) and, for production or other languages, creates a write token (the credential your app uses to send data). New to Logfire? Start with Getting Started.

Installation

Install logfire with the sqlalchemy extra:

Terminal
pip install 'logfire[sqlalchemy]'

Usage

Call logfire.configure(), then logfire.instrument_sqlalchemy() with your engine. A minimal example you can run with python main.py:

main.py
from sqlalchemy import create_engine

import logfire

logfire.configure()

engine = create_engine('sqlite:///:memory:')
logfire.instrument_sqlalchemy(engine=engine)

Verify it worked

Run a query through your engine, then open the Live view. Within a few seconds you’ll see a span for the query, with its duration and the SQL it ran, nested under the request span if you’ve also instrumented your web framework.

Troubleshooting

Not seeing queries? Check that logfire.configure() ran before instrument_sqlalchemy(), that your write token is set, that you passed your engine (or engines), and that you called the instrument function exactly once.

Advanced

The keyword arguments of logfire.instrument_sqlalchemy() are passed straight to the OpenTelemetry SQLAlchemyInstrumentor().instrument() method. See the OpenTelemetry SQLAlchemy instrumentation docs for the full option list.

Reference