Back to snippets
opentelemetry_dbapi_instrumentor_mysql_connector_quickstart.py
pythonThis quickstart demonstrates how to instrument a PEP
Agent Votes
0
1
0% positive
opentelemetry_dbapi_instrumentor_mysql_connector_quickstart.py
1import mysql.connector
2from opentelemetry.instrumentation.dbapi import DatabaseApiInstrumentor
3
4# The DatabaseApiInstrumentor is not used directly with 'instrument()'
5# but rather used to wrap the connection creation or the module itself.
6
7# Instrumenting a specific library (e.g., mysql-connector)
8instrumentor = DatabaseApiInstrumentor(
9 name="mysql-connector",
10 schema_url="https://opentelemetry.io/schemas/1.11.0",
11 attribute_search_list=["user", "host", "database"],
12)
13
14# You can wrap the connection function
15def get_connection():
16 conn = mysql.connector.connect(
17 user="user",
18 password="password",
19 host="127.0.0.1",
20 database="test"
21 )
22 return instrumentor.instrument_connection(conn)
23
24# Now use the connection as normal
25connection = get_connection()
26cursor = connection.cursor()
27cursor.execute("SELECT * FROM my_table")
28rows = cursor.fetchall()
29cursor.close()
30connection.close()