SQLAlchemy
The logfire.instrument_sqlalchemy()
method will create a span for every query executed by a SQLAlchemy engine.
Installation¶
Install logfire
with the sqlalchemy
extra:
pip install 'logfire[sqlalchemy]'
uv add 'logfire[sqlalchemy]'
Usage¶
Let's see a minimal example below. You can run it with python main.py
:
main.py
import logfire
from sqlalchemy import create_engine
logfire.configure()
engine = create_engine("sqlite:///:memory:")
logfire.instrument_sqlalchemy(engine=engine)
main.py
import logfire
from sqlalchemy import create_engine
logfire.configure()
engine_one = create_engine("sqlite:///:memory:")
engine_two = create_engine("sqlite:///:memory:")
logfire.instrument_sqlalchemy(engines=[engine_one, engine_two])
The keyword arguments of logfire.instrument_sqlalchemy()
are passed to the SQLAlchemyInstrumentor().instrument()
method of the OpenTelemetry SQLAlchemy Instrumentation package, read more about it here.
Warning
It's best to use the engine
or engines
arguments. If no engine is specified, then instrument_sqlalchemy
may
only work if it's called before sqlalchemy
is imported, in which case all engines are instrumented.
Tip
If you use SQLModel, you can use the same SQLAlchemyInstrumentor
to instrument it.