Skip to content

SQLite3

The logfire.instrument_sqlite3() method can be used to instrument the sqlite3 standard library module. This will automatically create spans for each SQL query executed.

Installation

Install logfire with the sqlite3 extra:

pip install 'logfire[sqlite3]'
uv add 'logfire[sqlite3]'
rye add logfire -E sqlite3
poetry add 'logfire[sqlite3]'

Usage

We can use the sqlite in-memory database to demonstrate the usage of the logfire.instrument_sqlite3() method.

You can either instrument the sqlite3 module or instrument a specific connection.

Instrument the module

Here's an example of instrumenting the sqlite3 module:

main.py
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')]

Instrument a connection

As mentioned, you can also instrument a specific connection. Here's an example:

main.py
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')]

Avoid using execute from sqlite3.Connection

The execute method from Connection is not instrumented!

You should use the execute method from the Cursor object instead.

See opentelemetry-python-contrib#3082 for more information.

logfire.instrument_sqlite3() uses the OpenTelemetry SQLite3 Instrumentation package, which you can find more information about here.