I would like to monitor the time taken by a query on my API's db. I so created the following function, using bookshelf-signals, a Bookshelf plugin. :
bookshelf.on('fetching', () => {
server.app.fetching = new Date().valueOf();
});
bookshelf.on('counting', () => {
server.app.fetching = new Date().valueOf();
});
bookshelf.on('fetched', () => {
server.statsd.gauge('db_query', new Date().valueOf() - server.app.fetching);
});
... so that I can retrieve the time just before and just after a fetch/count; I did the same with deleting-deleted and saving-saved.
What I think I fail to understand is when fetching and fetched are supposed to be triggered... When I tried to to see when fetching and fetched were triggered, basically it ended up with this :
'fetching event A'
'fetching event B'
'fetching event C'
'fetched event C'
'fetched event B'
'fetched event A'
Resulting in the timers returning wrong values obliviously, do you have any lead/clue ?
I also saw that one could trigger 'query' events on Knex, and thought of using this as an alternative solution. However, it seems that it only works if I specify the table where I query, ie :
knex('whatever_table').on('query', () => {///});
Making it impracticable in the case where I want to apply an event handler on every model... I think I should stick with Bookshelf, but how can I do with the way the events are handled?
Thank you in advance!
Based on Mikael Lepistö snippet I came up with this :
And I then call the function when I start the server - I am working with Hapijs.
EDIT: sdc is a statsd client, I use it to send the DB time :)
I just wrote some small test code how to trace transaction duration with knex.
https://runkit.com/embed/679qu91ylu4w
The same king of approach should work also for query timing. To prevent timer bookkeeping from leaking memory you should add some cleanup code though.
Query duration timer should be started in
query
event and stopped inquery-response
orquery-error
depending which one triggers first.To be able to match
query
-query-response
pairquerySpec.__knexQueryUid
attribute can be used.