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.
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 the
OpenTelemetry MySQL Instrumentation package,
which you can find more information about here.