Last active
September 10, 2023 19:44
-
-
Save ethanpil/4ca4e4306ff8ec279df611720fc430a6 to your computer and use it in GitHub Desktop.
WordPress Log All DB Queries To File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Plugin Name: WordPress Log All DB Queries To File | |
* Plugin URI: http://example.com/plugin-name-uri/ | |
* Description: All database queries will be logged to uploads/sql_log.txt activated. | |
* Version: 1.0.0 | |
* Author: Ethan Piliavin | |
* Author URI: http://piliavin.com/ | |
* License: GPL-2.0+ | |
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt | |
* Text Domain: log-all-db-to-file | |
* Domain Path: /languages | |
*/ | |
// If this file is called directly, abort. | |
if ( ! defined( 'WPINC' ) ) { | |
die; | |
} | |
function log_all_db_to_file_savequeries() { | |
$class = 'notice notice-warning'; | |
$message = __( "WordPress Log All DB Queries To File requires that you add the following to wp-config.php: <pre>define('SAVEQUERIES', true);</pre> ", 'log-all-db-to-file' ); | |
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) ); | |
} | |
if (!defined('SAVEQUERIES')) { | |
add_action( 'admin_notices', 'log_all_db_to_file_savequeries' ); | |
} | |
//Notify admin that were logging | |
function log_all_db_to_file_warning() { | |
$class = 'notice notice-warning'; | |
$message = __( 'WordPress Log All DB Queries To File is activated. All database queries are logged to uploads/sql_log.txt. This is a security risk and should be disabled as soon as possible!', 'log-all-db-to-file' ); | |
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) ); | |
} | |
add_action( 'admin_notices', 'log_all_db_to_file_warning' ); | |
//Add the logger | |
add_action('shutdown', 'sql_logger'); | |
function sql_logger() { | |
global $wpdb; | |
$log_file = fopen(trailingslashit(WP_CONTENT_DIR) . 'uploads/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"); | |
// Alternate reality - define( 'WP_DEBUG', true ); in wp-config.php and the logs will just go the wordpress debug.log file | |
// error_log($q[0] . " - ($q[1] s)"); | |
} | |
fclose($log_file); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment