Skip to content

Instantly share code, notes, and snippets.

@jeremyfelt
Created February 29, 2024 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyfelt/307a3eb497443a74c7d411428433fb05 to your computer and use it in GitHub Desktop.
Save jeremyfelt/307a3eb497443a74c7d411428433fb05 to your computer and use it in GitHub Desktop.
Store DB queries throughout request
<?php
add_action( 'muplugins_loaded', 'cac_temp_log_db_queries_as_json', 9999 );
add_action( 'plugins_loaded', 'cac_temp_log_db_queries_as_json', 9999 );
add_action( 'init', 'cac_temp_log_db_queries_as_json', 9999 );
add_action( 'shutdown', 'cac_temp_log_db_queries_as_json', 9999 );
/**
* Log all database queries as lines of JSON.
*/
function cac_temp_log_db_queries_as_json() {
global $wpdb;
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
$log_file = ABSPATH . '/wp-content/cac-query-log.json';
$records = '';
$request_domain = $_SERVER['HTTP_HOST'];
$request_uri = $_SERVER['REQUEST_URI'];
foreach( $wpdb->queries as $query ) {
$records .= wp_json_encode(
(object) array(
'query' => $query[0],
'time' => $query[1],
'call' => $query[2],
'domain' => $request_domain,
'uri' => $request_uri,
)
) . "\n";
}
file_put_contents( $log_file, $records, FILE_APPEND );
// Clear global query data.
$wpdb->queries = array();
}
}
<?php
add_action( 'muplugins_loaded', 'cac_temp_log_db_queries_as_text', 9999 );
add_action( 'plugins_loaded', 'cac_temp_log_db_queries_as_text', 9999 );
add_action( 'init', 'cac_temp_log_db_queries_as_text', 9999 );
add_action( 'shutdown', 'cac_temp_log_db_queries_as_text', 9999 );
/**
* Log all database queries to pipe delimited lines in a text file.
*/
function cac_temp_log_db_queries_as_text() {
global $wpdb;
if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
$log_file = ABSPATH . '/wp-content/cac-query-log.txt';
$records = '';
$request_domain = $_SERVER['HTTP_HOST'];
$request_uri = $_SERVER['REQUEST_URI'];
foreach( $wpdb->queries as $query ) {
$records .= sprintf(
"%s | %s | %s | %s | %s\n",
$query[0],
$query[1],
$query[2],
$request_domain,
$request_uri
);
}
file_put_contents( $log_file, $records, FILE_APPEND );
// Clear global query data.
$wpdb->queries = array();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment