Skip to content

MySQL's

logfire.instrument_mysql() Method can be used to use Logfire detection MySQL Connector/Python Database driver that creates a span for each query.

install

Install logfire using mysql extra:

{{ install_logfire(extras=['mysql']) }}

usage

Let's set up a MySQL database using Docker and run a Python script that connects to the database using MySQL connectors to demonstrate how to useLogfirewith MySQL.

Using Docker to set up MySQL database

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

docker run --name mysql \
    -e MYSQL_ROOT_PASSWORD=secret \
    -e MYSQL_DATABASE=database \
    -e MYSQL_USER=user \
    -e MYSQL_PASSWORD=secret \
    -p 3306:3306 -d mysql

This command does the following:

  • --name mysql Name the container "mysql."

  • -e MYSQL_ROOT_PASSWORD=secret Set the root password to "secret."

  • -e MYSQL_DATABASE=database Create a new database named database.

  • -e MYSQL_USER=user Create a new user named "user".

  • -e MYSQL_PASSWORD=secret Set the password for the new user to "secret."

  • -p 3306:3306 Map port 3306 in Docker to port 3306 on the host.

  • -d mysql Run the container in the background and print the container ID. The image is "mysql".

run a 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() use OpenTelemetry MySQL Instrumentation Bag, you can here Find more information about the package.


本文总阅读量次