Target.php 8.2 KB
Newer Older
w  
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\logging;

Qiang Xue committed
10 11
use yii\base\InvalidConfigException;

w  
Qiang Xue committed
12 13 14
/**
 * Target is the base class for all log target classes.
 *
w  
Qiang Xue committed
15 16 17
 * A log target object will filter the messages logged by [[Logger]] according
 * to its [[levels]] and [[categories]] properties. It may also export the filtered
 * messages to specific destination defined by the target, such as emails, files.
w  
Qiang Xue committed
18
 *
Qiang Xue committed
19 20 21
 * Level filter and category filter are combinatorial, i.e., only messages
 * satisfying both filter conditions will be handled. Additionally, you
 * may specify [[except]] to exclude messages of certain categories.
w  
Qiang Xue committed
22
 *
Qiang Xue committed
23 24
 * @property integer $levels the message levels that this target is interested in.
 *
w  
Qiang Xue committed
25 26 27
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
28
abstract class Target extends \yii\base\Component
w  
Qiang Xue committed
29 30 31 32 33
{
	/**
	 * @var boolean whether to enable this log target. Defaults to true.
	 */
	public $enabled = true;
w  
Qiang Xue committed
34 35 36 37
	/**
	 * @var array list of message categories that this target is interested in. Defaults to empty, meaning all categories.
	 * You can use an asterisk at the end of a category so that the category may be used to
	 * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
Qiang Xue committed
38
	 * categories starting with 'yii\db\', such as 'yii\db\Connection'.
w  
Qiang Xue committed
39 40 41 42 43 44 45
	 */
	public $categories = array();
	/**
	 * @var array list of message categories that this target is NOT interested in. Defaults to empty, meaning no uninteresting messages.
	 * If this property is not empty, then any category listed here will be excluded from [[categories]].
	 * You can use an asterisk at the end of a category so that the category can be used to
	 * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
Qiang Xue committed
46
	 * categories starting with 'yii\db\', such as 'yii\db\Connection'.
w  
Qiang Xue committed
47 48
	 * @see categories
	 */
Qiang Xue committed
49
	public $except = array();
w  
Qiang Xue committed
50
	/**
Qiang Xue committed
51
	 * @var boolean whether to log a message containing the current user name and ID. Defaults to false.
w  
Qiang Xue committed
52
	 * @see \yii\web\User
w  
Qiang Xue committed
53
	 */
w  
Qiang Xue committed
54
	public $logUser = false;
w  
Qiang Xue committed
55
	/**
w  
Qiang Xue committed
56 57 58
	 * @var array list of the PHP predefined variables that should be logged in a message.
	 * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be logged.
	 * Defaults to `array('_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER')`.
w  
Qiang Xue committed
59
	 */
w  
Qiang Xue committed
60
	public $logVars = array('_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER');
Qiang Xue committed
61
	/**
Qiang Xue committed
62 63 64
	 * @var integer how many messages should be accumulated before they are exported.
	 * Defaults to 1000. Note that messages will always be exported when the application terminates.
	 * Set this property to be 0 if you don't want to export messages until the application terminates.
Qiang Xue committed
65
	 */
Qiang Xue committed
66
	public $exportInterval = 1000;
w  
Qiang Xue committed
67
	/**
w  
Qiang Xue committed
68
	 * @var array the messages that are retrieved from the logger so far by this log target.
w  
Qiang Xue committed
69
	 */
Qiang Xue committed
70
	private $_messages = array();
w  
Qiang Xue committed
71

Qiang Xue committed
72 73
	private $_levels = 0;

w  
Qiang Xue committed
74
	/**
w  
Qiang Xue committed
75
	 * Exports log messages to a specific destination.
Qiang Xue committed
76 77 78
	 * Child classes must implement this method.
	 * @param array $messages the messages to be exported. See [[Logger::messages]] for the structure
	 * of each message.
w  
Qiang Xue committed
79
	 */
Qiang Xue committed
80
	abstract public function export($messages);
w  
Qiang Xue committed
81 82

	/**
w  
Qiang Xue committed
83 84 85 86 87 88
	 * Processes the given log messages.
	 * This method will filter the given messages with [[levels]] and [[categories]].
	 * And if requested, it will also export the filtering result to specific medium (e.g. email).
	 * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
	 * of each message.
	 * @param boolean $final whether this method is called at the end of the current application
w  
Qiang Xue committed
89
	 */
Qiang Xue committed
90
	public function collect($messages, $final)
w  
Qiang Xue committed
91
	{
Qiang Xue committed
92 93
		$this->_messages = array($this->_messages, $this->filterMessages($messages));
		$count = count($this->_messages);
Qiang Xue committed
94
		if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
Qiang Xue committed
95 96
			if (($context = $this->getContextMessage()) !== '') {
				$this->_messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME);
w  
Qiang Xue committed
97
			}
Qiang Xue committed
98 99
			$this->export($this->_messages);
			$this->_messages = array();
w  
Qiang Xue committed
100 101 102
		}
	}

w  
Qiang Xue committed
103 104 105 106 107 108
	/**
	 * Generates the context information to be logged.
	 * The default implementation will dump user information, system variables, etc.
	 * @return string the context information. If an empty string, it means no context information.
	 */
	protected function getContextMessage()
w  
Qiang Xue committed
109
	{
w  
Qiang Xue committed
110
		$context = array();
Qiang Xue committed
111
		if ($this->logUser && ($user = \Yii::$app->getComponent('user', false)) !== null) {
w  
Qiang Xue committed
112 113 114 115 116 117 118
			$context[] = 'User: ' . $user->getName() . ' (ID: ' . $user->getId() . ')';
		}

		foreach ($this->logVars as $name) {
			if (!empty($GLOBALS[$name])) {
				$context[] = "\${$name} = " . var_export($GLOBALS[$name], true);
			}
w  
Qiang Xue committed
119
		}
w  
Qiang Xue committed
120 121

		return implode("\n\n", $context);
w  
Qiang Xue committed
122 123
	}

Qiang Xue committed
124 125
	/**
	 * @return integer the message levels that this target is interested in. This is a bitmap of
Qiang Xue committed
126
	 * level values. Defaults to 0, meaning  all available levels.
Qiang Xue committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	 */
	public function getLevels()
	{
		return $this->_levels;
	}

	/**
	 * Sets the message levels that this target is interested in.
	 *
	 * The parameter can be either an array of interested level names or an integer representing
	 * the bitmap of the interested level values. Valid level names include: 'error',
	 * 'warning', 'info', 'trace' and 'profile'; valid level values include:
	 * [[Logger::LEVEL_ERROR]], [[Logger::LEVEL_WARNING]], [[Logger::LEVEL_INFO]],
	 * [[Logger::LEVEL_TRACE]] and [[Logger::LEVEL_PROFILE]].
	 *
	 * For example,
	 *
	 * ~~~
	 * array('error', 'warning')
	 * // which is equivalent to:
	 * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING
	 * ~~~
	 *
	 * @param array|integer $levels message levels that this target is interested in.
	 * @throws InvalidConfigException if an unknown level name is given
	 */
	public function setLevels($levels)
	{
		static $levelMap = array(
			'error' => Logger::LEVEL_ERROR,
			'warning' => Logger::LEVEL_WARNING,
			'info' => Logger::LEVEL_INFO,
			'trace' => Logger::LEVEL_TRACE,
			'profile' => Logger::LEVEL_PROFILE,
		);
		if (is_array($levels)) {
			$this->_levels = 0;
			foreach ($levels as $level) {
				if (isset($levelMap[$level])) {
					$this->_levels |= $levelMap[$level];
				} else {
					throw new InvalidConfigException("Unrecognized level: $level");
				}
			}
		} else {
			$this->_levels = $levels;
		}
	}

w  
Qiang Xue committed
176
	/**
w  
Qiang Xue committed
177 178 179 180 181
	 * Filters the given messages according to their categories and levels.
	 * @param array $messages messages to be filtered
	 * @return array the filtered messages.
	 * @see filterByCategory
	 * @see filterByLevel
w  
Qiang Xue committed
182
	 */
w  
Qiang Xue committed
183
	protected function filterMessages($messages)
w  
Qiang Xue committed
184
	{
Qiang Xue committed
185 186
		$levels = $this->getLevels();

w  
Qiang Xue committed
187
		foreach ($messages as $i => $message) {
Qiang Xue committed
188
			if ($levels && !($levels & $message[1])) {
w  
Qiang Xue committed
189 190 191 192 193 194
				unset($messages[$i]);
				continue;
			}

			$matched = empty($this->categories);
			foreach ($this->categories as $category) {
195
				if ($message[2] === $category || substr($category, -1) === '*' && strpos($message[2], rtrim($category, '*')) === 0) {
w  
Qiang Xue committed
196 197 198 199 200 201
					$matched = true;
					break;
				}
			}

			if ($matched) {
Qiang Xue committed
202
				foreach ($this->except as $category) {
w  
Qiang Xue committed
203 204 205 206 207 208 209 210 211 212 213 214 215
					$prefix = rtrim($category, '*');
					foreach ($messages as $i => $message) {
						if (strpos($message[2], $prefix) === 0 && ($message[2] === $category || $prefix !== $category)) {
							$matched = false;
							break;
						}
					}
				}
			}

			if (!$matched) {
				unset($messages[$i]);
			}
w  
Qiang Xue committed
216
		}
w  
Qiang Xue committed
217
		return $messages;
w  
Qiang Xue committed
218 219 220
	}

	/**
w  
Qiang Xue committed
221 222 223 224
	 * Formats a log message.
	 * The message structure follows that in [[Logger::messages]].
	 * @param array $message the log message to be formatted.
	 * @return string the formatted message
w  
Qiang Xue committed
225
	 */
w  
Qiang Xue committed
226
	public function formatMessage($message)
w  
Qiang Xue committed
227
	{
Qiang Xue committed
228 229 230 231 232 233 234 235 236 237 238 239 240
		static $levels = array(
			Logger::LEVEL_ERROR => 'error',
			Logger::LEVEL_WARNING => 'warning',
			Logger::LEVEL_INFO => 'info',
			Logger::LEVEL_TRACE => 'trace',
			Logger::LEVEL_PROFILE_BEGIN => 'profile begin',
			Logger::LEVEL_PROFILE_END => 'profile end',
		);
		list($text, $level, $category, $timestamp) = $message;
		$level = isset($levels[$level]) ? $levels[$level] : 'unknown';
		if (!is_string($text)) {
			$text = var_export($text, true);
		}
Qiang Xue committed
241 242
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
		return date('Y/m/d H:i:s', $timestamp) . " [$ip] [$level] [$category] $text\n";
w  
Qiang Xue committed
243 244
	}
}