WP-DB Add query_done Action for Performance Logging Plugins
|Reported by:||sexytyranno||Owned by:|
Attached is a patch I'm using locally to implement some performance logging with WP queries. I often use this in combination with a plug-in to determine what's causing a site to slow down (in cases where it's hard to reproduce it).
I've also extended the logged query data to have a "time_start" value as the 4th parameter to the logged query data (wpdb::queries), as knowing when a query started running can add perspective to page loads, which could otherwise be lost. The additional cost of this fourth parameter is nominal. (1000 queries results in maybe 10KB memory, assuming a 64-bit decimal encoding, plus the potential added array overhead)
This additional tidbit of information can be useful in narrowing down where exactly a slow-down is occurring if it's not database related, as it lets someone analyzing the data know between these two queries there was a large delay somewhere within the PHP code, and we have the two caller values to understand what was happening at the time.
PLUGIN DEVELOPER CONCERNS:
Due to the potential issues developers may encounter, it should be documented that any responder to query_done should
- USE IT ONLY WHEN ABSOLUTELY NECESSARY. Additionally, PROCESSING DONE WITHIN A QUERY_DONE RESPONDER SHOULD BE *MINIMAL*. query_done has the potential to be called many times after plug-ins are all loaded, and misuse of it can cause severe performance issues.
- Not use the calling $wpdb, as it will corrupt the state of wpdb, breaking the site (including the admin log-in section). If you want to log to the database, you must not even use the wpdb::dbh. You should instantiate your own "local" wpdb, or spin your own simple mysql_connect + mysql_select_db + mysql_query.
- If they're using an instance of WPDB to log the performance output, they MUST use a handler-specific flag indicating that they're currently responding to one, to avoid creating infinite recursion. Not using such a flag will cause PHP to crash.