How to log all SQL queries in WordPress

How do you get a complete log of the SQL queries done when a request is made? You could use a plugin for that, but sometimes it may be easier to a few lines of code and after the job is done, remove them.

In my case, I needed to know where some data, that comes from a custom options panel, in a third-party plugin, is saved. It was hard to find it in the code. So I ended up with a log of the SQL queries. Then I searched for UPDATE queries and found the table that was affected. That way I was able to find it and after that could create my own function that would use that data.

First of all, we need to define a constant that will force WordPress to save all queries.

Add the following code in wp-config.php

define('SAVEQUERIES', true);

Next, we need to save them somewhere. I’ll instruct it to save them in a file under the uploads folder. I choose uploads it because it already should be writable by WP.

Add the following code in the functions.php file of your active theme or in a custom plugin.


add_action('shutdown', 'mySqlLogger');
function mySqlLogger()
{
    global $wpdb;

    $file = fopen(trailingslashit(WP_CONTENT_DIR) . 'uploads/sqlLogs.txt', 'a');

    fwrite($file, "\n\n------ NEW REQUEST [" . date("F j, Y, g:i:s a") . "] ------\n\n");

    foreach ($wpdb->queries as $q) {
        fwrite($file, $q[0] . " - ($q[1] s)" . "\n\n");
    }

    fclose($file);
}

Now if you reload a page, make an ajax request, or save something, all SQL requests will be saved in uploads/sqlLogs.txt

Simple like that!

Warning! Once you’ve found what you needed, make sure to remove this code from your theme/plugin. This should never run in a production environment. It’s intended only for development purposes.

Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

    Your email address will not be published.