class.jetpack-search-performance-logger.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. class Jetpack_Search_Performance_Logger {
  3. /**
  4. * @var Jetpack_Search_Performance_Logger
  5. **/
  6. private static $instance = null;
  7. private $current_query = null;
  8. private $query_started = null;
  9. private $stats = null;
  10. static function init() {
  11. if ( is_null( self::$instance ) ) {
  12. self::$instance = new Jetpack_Search_Performance_Logger;
  13. }
  14. return self::$instance;
  15. }
  16. private function __construct() {
  17. $this->stats = array();
  18. add_action( 'pre_get_posts', array( $this, 'begin_log_query' ), 10, 1 );
  19. add_action( 'did_jetpack_search_query', array( $this, 'log_jetpack_search_query' ) );
  20. add_filter( 'found_posts', array( $this, 'log_mysql_query' ), 10, 2 );
  21. add_action( 'wp_footer', array( $this, 'print_stats' ) );
  22. }
  23. public function begin_log_query( $query ) {
  24. if ( $this->should_log_query( $query ) ) {
  25. $this->query_started = microtime( true );
  26. $this->current_query = $query;
  27. }
  28. }
  29. public function log_mysql_query( $found_posts, $query ) {
  30. if ( $this->current_query === $query ) {
  31. $duration = microtime( true ) - $this->query_started;
  32. if ( $duration < 60 ) { // eliminate outliers, likely tracking errors
  33. $this->record_query_time( $duration, false );
  34. }
  35. $this->reset_query_state();
  36. }
  37. return $found_posts;
  38. }
  39. public function log_jetpack_search_query() {
  40. $duration = microtime( true ) - $this->query_started;
  41. if ( $duration < 60 ) { // eliminate outliers, likely tracking errors
  42. $this->record_query_time( $duration, true );
  43. }
  44. $this->reset_query_state();
  45. }
  46. private function reset_query_state() {
  47. $this->query_started = null;
  48. $this->current_query = null;
  49. }
  50. private function should_log_query( $query ) {
  51. return $query->is_main_query() && $query->is_search();
  52. }
  53. private function record_query_time( $duration, $was_jetpack_search ) {
  54. $this->stats[] = array( $was_jetpack_search, intval( $duration * 1000 ) );
  55. }
  56. public function print_stats() {
  57. $beacons = array();
  58. if ( ! empty( $this->stats ) ) {
  59. foreach( $this->stats as $stat ) {
  60. $search_type = $stat[0] ? 'es' : 'mysql';
  61. $beacons[] = "%22jetpack.search.{$search_type}.duration:{$stat[1]}|ms%22";
  62. }
  63. $encoded_json = '{%22beacons%22:[' . implode(',', $beacons ) . ']}';
  64. $encoded_site_url = urlencode( site_url() );
  65. $url = "https://pixel.wp.com/boom.gif?v=0.9&u={$encoded_site_url}&json={$encoded_json}";
  66. echo '<img src="' . $url . '" width="1" height="1" style="display:none;" alt=":)"/>';
  67. }
  68. }
  69. }