sitemap-logger.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * A message logger for the Jetpack Sitemap module.
  4. *
  5. * @package Jetpack
  6. * @since 4.8.0
  7. */
  8. /**
  9. * Handles logging errors and debug messages for sitemap generator.
  10. *
  11. * A Jetpack_Sitemap_Logger object keeps track of its birth time as well
  12. * as a "unique" ID string. Calling the report() method writes a message
  13. * to the PHP error log as well as the ID string for easier grepping.
  14. *
  15. * @since 4.8.0
  16. */
  17. class Jetpack_Sitemap_Logger {
  18. /**
  19. * A unique-ish string for each logger, enabling us to grep
  20. * for the messages written by an individual generation phase.
  21. *
  22. * @access private
  23. * @since 4.8.0
  24. * @var string $key The key string.
  25. */
  26. private $key;
  27. /**
  28. * The birth time of this object in microseconds.
  29. *
  30. * @access private
  31. * @since 4.8.0
  32. * @var int $starttime The birth time.
  33. */
  34. private $starttime;
  35. /**
  36. * Initializes a new logger object.
  37. *
  38. * @access public
  39. * @since 4.8.0
  40. *
  41. * @param string $message An optional message string to be written to the debug log on initialization.
  42. */
  43. public function __construct( $message = null ) {
  44. $this->key = wp_generate_password( 5, false );
  45. $this->starttime = microtime( true );
  46. if ( ! is_null( $message ) ) {
  47. $this->report( $message );
  48. }
  49. return;
  50. }
  51. /**
  52. * Writes a string to the debug log, including the logger's ID string.
  53. *
  54. * @access public
  55. * @since 4.8.0
  56. *
  57. * @param string $message The string to be written to the log.
  58. * @param boolean $is_error If true, $message will be logged even if JETPACK_DEV_DEBUG is not enabled
  59. */
  60. public function report( $message, $is_error = false ) {
  61. $message = 'jp-sitemap-' . $this->key . ': ' . $message;
  62. if ( ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
  63. return;
  64. }
  65. if ( ! $is_error && ! ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) ) {
  66. return;
  67. }
  68. error_log( $message );
  69. return;
  70. }
  71. /**
  72. * Writes the elapsed lifetime of the logger to the debug log, with an optional message.
  73. *
  74. * @access public
  75. * @since 4.8.0
  76. *
  77. * @param string $message The optional message string. Default is the empty string.
  78. */
  79. public function time( $message = '' ) {
  80. $time = round( microtime( true ) - $this->starttime, 3 );
  81. $this->report( $message . ' ' . $time . ' seconds elapsed.' );
  82. return;
  83. }
  84. }