I want to plugin in nodejs' debug into node-mysql, in order to log all the queries. I'd rather not wrap all the calls to node-mysql, because of the formatting and the many combinations of arguments.
I'm using bluebird to make promises so I can't really use the return value of connection.query(). connection.queryAsync() doesn't give me access to the return object.
It would be nice if there was a way to plug it in, maybe an event on the connection/pool object. That way I don't have to think about writing the code that does the logging.
Hi @q42jaap , that seems like a pretty good idea. Any proposal on what would be a good way to go about it that would satisfy your use-case?
Hi, sorry it took a while for me to respond.
I would think a Connection level event system seems a good idea.
connection.on('query', function(query) { console.log(query.sql) });
as an added bonus, it may be nice to also add it to a Pool:
pool.on('query', function(query) { console.log(query.sql) });
Something along these lines?
+1
Perhaps the following code may work?
connection.on('enqueue', function (sequence) {
if (sequence instanceof mysql.Sequences.Query) {
console.log(sequence.sql);
}
});
The response didn't actually lay-out the use-case, only really what you envisioned the API to be. Can you please layout the use-case for the event? For example, why emit queries both in the enqueue event as well as again on a query event?
Hi @dougwilson,
I did not know this! This may very well work for my use case. I just want to see all the query's while developing. Enqueue is probably exactly what I'm looking for.
As a last thing, does the pool also have this enqueue event?
As a last thing, does the pool also have this enqueue event?
It does, but it has a different meaning: it means a connection request has been enqueued. If you want to monitor from the pool-level, just combine the connection event on the pool plus the enqueue event on the connection:
pool.on('connection', function (connection) {
connection.on('enqueue', function (sequence) {
if (sequence instanceof mysql.Sequences.Query) {
console.log(sequence.sql);
}
});
});
This is super helpful, thanks a lot!
No problem!
@dougwilson This doesn't seem to work anymore. I am getting TypeError: Cannot read property 'Query' of undefined
Here is the code:
if (nconf.get('dev')) {
Database.pool.on('connection', (connection) => {
connection.on('enqueue', (sequence) => {
if (sequence instanceof mysql.Sequences.Query) {
winston.info(sequence.sql);
}
});
});
}
This is how I am doing it now :)
pool.on('connection', function(connection) {
connection.on('enqueue', function(sequence) {
// if (sequence instanceof mysql.Sequence.Query) {
if ('Query' === sequence.constructor.name) {
console.log(sequence.sql);
}
});
});
Most helpful comment
This is how I am doing it now :)