Blog

Logging WordPress SQL Queries

WordPress

To log the database queries executed by WordPress, you need to enable SAVEQUERIES in the wp-config.php file. Add the following entry:

define( 'SAVEQUERIES', true );

Then, add the following code to a plugin or to the functions.php file of the active theme:

add_action( 'shutdown', function () {
    global $wpdb;
    $log_stack = true;

    $log_file = fopen( ABSPATH . '/wp-content/sql.log', 'a' );

    fwrite( $log_file, PHP_EOL . PHP_EOL . "############################################################" . PHP_EOL . PHP_EOL . date( "F j, Y, g:i:s a" ) . PHP_EOL );

    foreach ( $wpdb->queries as $query ) {
        fwrite( $log_file, $query[0] . " - ($query[1] s)" );
        if ( $log_stack ) {
            fwrite( $log_file, PHP_EOL . "[Stack]: $query[2]" . PHP_EOL . PHP_EOL );
        } else {
            fwrite( $log_file, PHP_EOL . PHP_EOL );
        }
    }
    fclose( $log_file );
} );

This method creates a file named wp-content/sql.log that contains all WordPress SQL queries.

NOTE: The file is publicly accessible and should be protected accordingly!