SQLite3
See every query your app runs through Python’s built-in sqlite3 module (the statement,
how long it took, and which ones failed) as a span (one unit of work with a name, a start, and a
duration) in Logfire. Related spans link together into a trace (the full journey of one request),
so a slow query shows up right next to the code that triggered it.
- Each query as a span, with its duration and any errors
- The SQL statement that ran
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 sqlite3 extra:
pip install 'logfire[sqlite3]'
uv add 'logfire[sqlite3]'
Add two lines to your app: logfire.configure() to connect to your project, and
logfire.instrument_sqlite3() to record every query. The
example below uses an in-memory database so you can run it as-is.
import sqlite3
import logfire
logfire.configure()
logfire.instrument_sqlite3()
with sqlite3.connect(':memory:') as connection:
cursor = connection.cursor()
cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
cursor.execute('SELECT * FROM users')
print(cursor.fetchall())
#> [(1, 'Alice')]
connection.close()
Run it with python main.py.
Run your program, then open your project in the Logfire web app and go to the Live view. Within a few seconds you should see a span for each query the script ran. Click one to see the SQL statement and how long it took.
Not seeing your queries in Logfire? Check these first:
logfire.configure()runs beforelogfire.instrument_sqlite3(). Configure the connection first, then instrument.- You call
instrument_sqlite3()exactly once. - You run queries through a cursor, not the connection. The
executemethod onsqlite3.Connectionis not instrumented; use theexecutemethod on aCursorinstead (see the note below). - Your write token is set. In local development, run
logfire projects use <your-project>; in production, set theLOGFIRE_TOKENenvironment variable. See Getting Started.
Instead of the whole module, you can instrument just one connection:
import sqlite3
import logfire
logfire.configure()
with sqlite3.connect(':memory:') as connection:
connection = logfire.instrument_sqlite3(connection)
cursor = connection.cursor()
cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
cursor.execute('SELECT * FROM users')
print(cursor.fetchall())
#> [(1, 'Alice')]
connection.close()
- API reference:
logfire.instrument_sqlite3() - Underlying OpenTelemetry package: SQLite3 instrumentation