Selective Realtime SQL Monitoring

While investigating unusual WordPress behavior, I needed a way to log all queries to a file for detailed analysis, but stream a subset to the console.

This wp-config parameter

define('SAVEQUERIES', true);

and snippet in functions.php (from Bob Sherron)

// 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);
}

logs all queries to sql_log.txt. On the server, I can then run

tail -f sql_log.txt | grep "WHERE \`option_name\` = 'sidebars_widgets'" | tee sidebars_widgets.txt

Note the backticks around option_name and single quotes around sidebars_widgets.

Breakdown of the individual commands:

tail -f sql_log.txt

Stream the end of sql_log.txt to stdout, as it’s updated

grep "WHERE \`option_name\` = 'sidebars_widgets'"

Filter only queries that update the row I’m interested in

tee sidebars_widgets.txt

Display the filtered lines on the console and write to sidebars_widgets.txt for later review

Categorized: Software

Leave a Reply

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