Skip to content

MySQL

The logfire.instrument_mysql() method can be used to instrument the MySQL Connector/Python database driver with Logfire, creating a span for every query.

Installation

Install logfire with the mysql extra:

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

Usage

Let's setup a MySQL database using Docker and run a Python script that connects to the database using MySQL connector to demonstrate how to use Logfire with MySQL.

Setup a MySQL Database Using Docker

First, we need to initialize a MySQL database. This can be easily done using Docker with the following command:

docker run --name mysql \  # (1)!
    -e MYSQL_ROOT_PASSWORD=secret \  # (2)!
    -e MYSQL_DATABASE=database \  # (3)!
    -e MYSQL_USER=user \  # (4)!
    -e MYSQL_PASSWORD=secret \  # (5)!
    -p 3306:3306 \  # (6)!
    -d mysql  # (7)!
  1. --name mysql: This defines the name of the Docker container.
  2. -e MYSQL_ROOT_PASSWORD=secret: This sets a password for the MySQL root user.
  3. -e MYSQL_DATABASE=database: This creates a new database named "database", the same as the one used in your Python script.
  4. -e MYSQL_USER=user: This sets a user for the MySQL server.
  5. -e MYSQL_PASSWORD=secret: This sets a password for the MySQL server.
  6. -p 3306:3306: This makes the MySQL instance available on your local machine under port 3306.
  7. -d mysql: This denotes the Docker image to be used, in this case, "mysql", and starts the container in detached mode.

Run the Python script

The following Python script connects to the MySQL database and executes some SQL queries:

import logfire
import mysql.connector

logfire.configure()

# To instrument the whole module:
logfire.instrument_mysql()

connection = mysql.connector.connect(
    host="localhost",
    user="user",
    password="secret",
    database="database",
    port=3306,
    use_pure=True,
)

# Or instrument just the connection:
# connection = logfire.instrument_mysql(connection)

with logfire.span('Create table and insert data'), connection.cursor() as cursor:
    cursor.execute(
        'CREATE TABLE IF NOT EXISTS test (id INT AUTO_INCREMENT PRIMARY KEY, num integer, data varchar(255));'
    )

    # Insert some data
    cursor.execute('INSERT INTO test (num, data) VALUES (%s, %s)', (100, 'abc'))
    cursor.execute('INSERT INTO test (num, data) VALUES (%s, %s)', (200, 'def'))

    # Query the data
    cursor.execute('SELECT * FROM test')
    results = cursor.fetchall()  # Fetch all rows
    for row in results:
        print(row)  # Print each row

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