Rails-Like SQL Query Logging in WordPress

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!

This entry was posted in Programming and tagged , . Bookmark the permalink.

3 Responses to Rails-Like SQL Query Logging in WordPress

  1. Very useful post! had to book mark it for safe keeping.

  2. Pingback: Wordpress Performance: Time Consuming MySQL Queries and Caching — Create A Website

  3. Pingback: SQL query logging in Wordpress | Space Babies

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>