Нет описания

sitemap-logger.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * A message logger for the Jetpack Sitemap module.
  4. *
  5. * @package automattic/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. }
  50. /**
  51. * Writes a string to the debug log, including the logger's ID string.
  52. *
  53. * @access public
  54. * @since 4.8.0
  55. *
  56. * @param string $message The string to be written to the log.
  57. * @param boolean $is_error If true, $message will be logged even if JETPACK_DEV_DEBUG is not enabled.
  58. */
  59. public function report( $message, $is_error = false ) {
  60. $message = 'jp-sitemap-' . $this->key . ': ' . $message;
  61. if ( ! ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
  62. return;
  63. }
  64. if ( ! $is_error && ! ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) ) {
  65. return;
  66. }
  67. error_log( $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
  68. }
  69. /**
  70. * Writes the elapsed lifetime of the logger to the debug log, with an optional message.
  71. *
  72. * @access public
  73. * @since 4.8.0
  74. *
  75. * @param string $message The optional message string. Default is the empty string.
  76. */
  77. public function time( $message = '' ) {
  78. $time = round( microtime( true ) - $this->starttime, 3 );
  79. $this->report( $message . ' ' . $time . ' seconds elapsed.' );
  80. }
  81. }