How can I debug queries sent via mysql2?

2k views Asked by At

From the mysql2 readme we read :

MySQL2 is mostly API compatible with mysqljs

Which package has an option defined as :

  • debug: Prints protocol details to stdout. Can be true/false or an array of packet type names that should be printed. (Default: false)

This option even has an example :

var connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']});

However, setting this option with either true, "ComQueryPacket" and/or "RowDataPacket" vomits a ton load of irrelevant data; all I care is to have the SQL query and variables being sent. How can this be done with this package?

1

There are 1 answers

1
Andrey Sidorov On

debug option only supports true/false values in mysql2. Easiest way to log all queries would be to monkey patch Connection.prototype.addCommand, example pseudocode:

let addCommand = Connection.prototype.addCommand
function loggingAddCommand(cmd) {
  if (cmd.constructor === Commands.Query) {
    console.log(`Adding query command, sql: ${cmd.sql}`);
  }
  this.addCommand(cmd);
}

connection.addCommand = loggingAddCommand;

I'll try to think about better api to make this easier. Maybe having "command" event on a connection? If we add this, above example would become conn.on('command_added', cmd => { /* ... */ })