Created
August 9, 2016 18:02
-
-
Save joehoyle/4169ca70bf824be144d8befb1f8c2d8a to your computer and use it in GitHub Desktop.
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: DB Query Backtrace | |
* Description: Add backtraces to MySQL Queries to enable backtracing from mysql slowlogs / process lists. | |
* Author: Joe Hoyle | |
* Version: 1.0 | |
*/ | |
namespace DB_Query_Backtrace; | |
add_filter( 'query', __NAMESPACE__ . '\\add_backtrace_to_query', 100 ); | |
/** | |
* Inject the backtrace on the end of all queres | |
* | |
* @param string $query | |
* @return string | |
*/ | |
function add_backtrace_to_query( $query ) { | |
/* | |
Backtrace: | |
0: this file | |
1: wp-db.php calling apply filters | |
2: wpdb::query() function call | |
3: wpdb::(get_col/get_var/get_results) | |
*/ | |
$backtrace = array_slice( debug_backtrace( false, 6 ), 4, 1 ); | |
$call = implode( ', ', array_map( __NAMESPACE__ . '\\backtrace_item_string_value', $backtrace ) ); | |
var_dump($call); | |
return $query . ' # Backtrace: ' . $call; | |
} | |
/** | |
* Transform an item from debug_backtrace() to a short human readable version. | |
* | |
* @param array $backtrace | |
* @return string | |
*/ | |
function backtrace_item_string_value( $backtrace ) { | |
return sprintf( | |
'%s%s( %s )', | |
$backtrace['class'] ? $backtrace['class'] . '::' : '', | |
$backtrace['function'], | |
implode( ', ', array_map( __NAMESPACE__ . '\\param_string_value', $backtrace['args'] ) ) | |
); | |
} | |
/** | |
* Get a human readable string for a param passed to a function. | |
* | |
* @param mixed $val | |
* @return string | |
*/ | |
function param_string_value( $val ) { | |
if ( is_object( $val ) ) { | |
return get_class( $val ); | |
} | |
$val = str_replace( "\n", '', var_export( $val, true ) ); | |
if ( strlen( $val ) > 100 ) { | |
$val = substr( $val, 0, 100 ) . '...'; | |
} | |
return $val; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment