Target.php 8.22 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
use Yii;
Qiang Xue committed
11
use yii\base\Component;
Qiang Xue committed
12 13
use yii\base\InvalidConfigException;

w  
Qiang Xue committed
14 15 16
/**
 * Target is the base class for all log target classes.
 *
w  
Qiang Xue committed
17 18 19
 * 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
20
 *
Qiang Xue committed
21 22 23
 * 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
24
 *
Qiang Xue committed
25 26
 * @property integer $levels the message levels that this target is interested in.
 *
w  
Qiang Xue committed
27 28 29
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
30
abstract class Target extends Component
w  
Qiang Xue committed
31 32 33 34 35
{
	/**
	 * @var boolean whether to enable this log target. Defaults to true.
	 */
	public $enabled = true;
w  
Qiang Xue committed
36 37 38 39
	/**
	 * @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
40
	 * categories starting with 'yii\db\', such as 'yii\db\Connection'.
w  
Qiang Xue committed
41 42 43 44 45 46 47
	 */
	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
48
	 * categories starting with 'yii\db\', such as 'yii\db\Connection'.
w  
Qiang Xue committed
49 50
	 * @see categories
	 */
Qiang Xue committed
51
	public $except = array();
w  
Qiang Xue committed
52
	/**
Qiang Xue committed
53
	 * @var boolean whether to log a message containing the current user name and ID. Defaults to false.
w  
Qiang Xue committed
54
	 * @see \yii\web\User
w  
Qiang Xue committed
55
	 */
w  
Qiang Xue committed
56
	public $logUser = false;
w  
Qiang Xue committed
57
	/**
w  
Qiang Xue committed
58 59 60
	 * @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
61
	 */
w  
Qiang Xue committed
62
	public $logVars = array('_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER');
Qiang Xue committed
63
	/**
Qiang Xue committed
64 65 66
	 * @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
67
	 */
Qiang Xue committed
68
	public $exportInterval = 1000;
w  
Qiang Xue committed
69
	/**
w  
Qiang Xue committed
70
	 * @var array the messages that are retrieved from the logger so far by this log target.
w  
Qiang Xue committed
71
	 */
Qiang Xue committed
72
	public $messages = array();
w  
Qiang Xue committed
73

Qiang Xue committed
74 75
	private $_levels = 0;

w  
Qiang Xue committed
76
	/**
w  
Qiang Xue committed
77
	 * Exports log messages to a specific destination.
Qiang Xue committed
78 79 80
	 * 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
81
	 */
Qiang Xue committed
82
	abstract public function export($messages);
w  
Qiang Xue committed
83 84

	/**
w  
Qiang Xue committed
85 86 87 88 89 90
	 * 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
91
	 */
Qiang Xue committed
92
	public function collect($messages, $final)
w  
Qiang Xue committed
93
	{
Qiang Xue committed
94 95
		$this->messages = array_merge($this->messages, $this->filterMessages($messages));
		$count = count($this->messages);
Qiang Xue committed
96
		if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
Qiang Xue committed
97
			if (($context = $this->getContextMessage()) !== '') {
Qiang Xue committed
98
				$this->messages[] = array($context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME);
w  
Qiang Xue committed
99
			}
Qiang Xue committed
100 101
			$this->export($this->messages);
			$this->messages = array();
w  
Qiang Xue committed
102 103 104
		}
	}

w  
Qiang Xue committed
105 106 107 108 109 110
	/**
	 * 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
111
	{
w  
Qiang Xue committed
112
		$context = array();
Qiang Xue committed
113 114 115
		if ($this->logUser && ($user = Yii::$app->getComponent('user', false)) !== null) {
			/** @var $user \yii\web\User */
			$context[] = 'User: ' . $user->getId();
w  
Qiang Xue committed
116 117 118 119 120 121
		}

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

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

Qiang Xue committed
127 128
	/**
	 * @return integer the message levels that this target is interested in. This is a bitmap of
Qiang Xue committed
129
	 * level values. Defaults to 0, meaning  all available levels.
Qiang Xue committed
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 176 177 178
	 */
	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
179
	/**
w  
Qiang Xue committed
180 181 182 183 184
	 * 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
185
	 */
w  
Qiang Xue committed
186
	protected function filterMessages($messages)
w  
Qiang Xue committed
187
	{
Qiang Xue committed
188 189
		$levels = $this->getLevels();

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

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

			if ($matched) {
Qiang Xue committed
205
				foreach ($this->except as $category) {
w  
Qiang Xue committed
206 207 208 209 210 211 212 213 214 215 216 217 218
					$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
219
		}
w  
Qiang Xue committed
220
		return $messages;
w  
Qiang Xue committed
221 222 223
	}

	/**
w  
Qiang Xue committed
224 225 226 227
	 * 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
228
	 */
w  
Qiang Xue committed
229
	public function formatMessage($message)
w  
Qiang Xue committed
230
	{
Qiang Xue committed
231 232 233 234 235 236 237 238 239 240 241 242 243
		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
244 245
		$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
246 247
	}
}