summaryrefslogtreecommitdiff
blob: 8e602b1122f31f95ed46bbc4637009f87a0de666 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/**
 * A message logger for the Jetpack Sitemap module.
 *
 * @package Jetpack
 * @since 4.8.0
 */

/**
 * Handles logging errors and debug messages for sitemap generator.
 *
 * A Jetpack_Sitemap_Logger object keeps track of its birth time as well
 * as a "unique" ID string. Calling the report() method writes a message
 * to the PHP error log as well as the ID string for easier grepping.
 *
 * @since 4.8.0
 */
class Jetpack_Sitemap_Logger {
	/**
	 * A unique-ish string for each logger, enabling us to grep
	 * for the messages written by an individual generation phase.
	 *
	 * @access private
	 * @since 4.8.0
	 * @var string $key The key string.
	 */
	private $key;

	/**
	 * The birth time of this object in microseconds.
	 *
	 * @access private
	 * @since 4.8.0
	 * @var int $starttime The birth time.
	 */
	private $starttime;

	/**
	 * Initializes a new logger object.
	 *
	 * @access public
	 * @since 4.8.0
	 *
	 * @param string $message An optional message string to be written to the debug log on initialization.
	 */
	public function __construct( $message = null ) {
		$this->key = wp_generate_password( 5, false );
		$this->starttime = microtime( true );
		if ( ! is_null( $message ) ) {
			$this->report( $message );
		}
		return;
	}

	/**
	 * Writes a string to the debug log, including the logger's ID string.
	 *
	 * @access public
	 * @since 4.8.0
	 *
	 * @param string $message The string to be written to the log.
	 */
	public function report( $message ) {
		if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			error_log( 'jp-sitemap-' . $this->key . ': ' . $message );
		}
		return;
	}

	/**
	 * Writes the elapsed lifetime of the logger to the debug log, with an optional message.
	 *
	 * @access public
	 * @since 4.8.0
	 *
	 * @param string $message The optional message string. Default is the empty string.
	 */
	public function time( $message = '' ) {
		$time = round( microtime( true ) - $this->starttime, 3 );
		$this->report( $message . ' ' . $time . ' seconds elapsed.' );
		return;
	}
}