Movatterモバイル変換


[0]ホーム

URL:


Skip to content

MySQL

Thelogfire.instrument_mysql() method can be used to instrument theMySQL Connector/Python database driver withLogfire, creating a span for every query.

Installation

Installlogfire with themysql extra:

pipinstall'logfire[mysql]'
uvadd'logfire[mysql]'

Usage

Let's setup a MySQL database using Docker and run a Python script that connects to the database using MySQL connector todemonstrate how to useLogfire 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:

dockerrun--namemysql\-eMYSQL_ROOT_PASSWORD=secret\-eMYSQL_DATABASE=database\-eMYSQL_USER=user\-eMYSQL_PASSWORD=secret\-p3306:3306\-dmysql

The command above will create a MySQL database, that you can connect withmysql://user:secret@0.0.0.0:3306/database.

Run the Python script

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

importlogfireimportmysql.connectorlogfire.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)withlogfire.span('Create table and insert data'),connection.cursor()ascursor:cursor.execute('CREATE TABLE IF NOT EXISTS test (id INT AUTO_INCREMENT PRIMARY KEY, num integer, data varchar(255));')# Insert some datacursor.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 datacursor.execute('SELECT * FROM test')results=cursor.fetchall()# Fetch all rowsforrowinresults:print(row)# Print each row

logfire.instrument_mysql() uses theOpenTelemetry MySQL Instrumentation package,which you can find more information abouthere.


[8]ページ先頭

©2009-2025 Movatter.jp