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:
In your functions.php, add this:
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.
[...] I have been looking at a client’s WordPress install the last few days. They have a large number of posts and page load times in general have been increasing. I installed some query logging based on the code in this article … Rails-Like SQL Query Logging in WordPress [...]
[...] tools like the console and the log. Well turns out you can have a sql log for WordPress as well! This post tells you how, and it [...]