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.
- 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
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.
Install logfire with the sqlalchemy extra:
pip install 'logfire[sqlalchemy]'
uv add 'logfire[sqlalchemy]'
Call logfire.configure(), then logfire.instrument_sqlalchemy() with your engine. A minimal example you can run with python main.py:
from sqlalchemy import create_engine
import logfire
logfire.configure()
engine = create_engine('sqlite:///:memory:')
logfire.instrument_sqlalchemy(engine=engine)
from sqlalchemy import create_engine
import logfire
logfire.configure()
engine_one = create_engine('sqlite:///:memory:')
engine_two = create_engine('sqlite:///:memory:')
logfire.instrument_sqlalchemy(engines=[engine_one, engine_two])
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.
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.
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.
logfire.instrument_sqlalchemy(): the Logfire API reference.- OpenTelemetry SQLAlchemy instrumentation: the underlying package.