Coming out of doing Rails development for the past couple years, there are several things that I have become pretty accustomed to that are somewhat aggravating not to have in the WordPress environment. The one thing that I miss the most though, is having a log of SQL queries to pore over and see what’s happening with the DB, and which queries are taking the longest. After some searching, I came across this post, which led me in the right direction. After some tweaking here is the result:
In your wp-config.php, add this line:
define('SAVEQUERIES', true);
In your functions.php, add this:
// outputs SQL queries to a log
add_action('shutdown', 'sql_logger');
function sql_logger() {
global $wpdb;
$log_file = fopen(ABSPATH.'/sql_log.txt', 'a');
fwrite($log_file, "//////////////////////////////////////////\n\n" . date("F j, Y, g:i:s a")."\n");
foreach($wpdb->queries as $q) {
fwrite($log_file, $q[0] . " - ($q[1] s)" . "\n\n");
}
fclose($log_file);
}
Jackpot! Now, you have a log file to go to town on. Enjoy!
Very useful post! had to book mark it for safe keeping.
Pingback: Wordpress Performance: Time Consuming MySQL Queries and Caching — Create A Website
Pingback: SQL query logging in Wordpress | Space Babies