Kategorier
Okategoriserade

MySQL ADO.NET tracing from Powershell

I needed to debug at Powershell script that uses MySQL Connectior .Net, and wanted to enable Tracing. This is fairly easy if you are using ODBC, but a little different when using the .Net Connector.

The basic outline is to use Tracing in the System.Diagnosticts namespace.

All the examples I found was based on using a app.config file as in this example: https://dev.mysql.com/doc/connector-net/en/connector-net-programming-tracing.html

But in PowerShell its not that easy, since the app.config is for the interpreter itself (powershell.exe), and not for the script.

After a couple of hours testing, I found that the driver has already instantiated all the necessary objects, you just have to connect it to a trace listener. Below is a snippet outlining the process:

# Load the assambly for MySQL
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")

# Create a trace listener that writes to a text file.
$traceListener = [System.Diagnostics.TextWriterTraceListener]::New("E:\log\trace.txt", "text_logger")

# Add the listener to the static MySQLTrace-object
[MySql.Data.MySqlClient.MySqlTrace]::Listeners.Add($traceListener)

#Set verbose loggin, otherwise you will not se a thing.
[MySql.Data.MySqlClient.MySqlTrace]::Switch.Level = "Verbose"

# Open Connection, make sure to add Logging=true; to the connection string
[MySql.Data.MySqlClient.MySqlConnection]$Connection  
$Connection.Open("Server=blabla,PORT=3306,UID=user,PWD=something;Logging=true;")

# ... do your DB stuff here.

# Close the trace listener to release the log file.
# This is is only nessecarry when runnting the code in ISE or other interactive environment.
# If the executing powershell process is exited, the log file will be released anyway.
$traceListener.Dispose()

Thats it, no app.config and no creations of trace sources!

Lämna ett svar

Din e-postadress kommer inte publiceras. Obligatoriska fält är märkta *