Target.php 8.18 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
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8
namespace yii\log;
w  
Qiang Xue committed
9

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.
Qiang Xue committed
71
	 * Please refer to [[Logger::messages]] for the details about the message structure.
w  
Qiang Xue committed
72
	 */
Qiang Xue committed
73
	public $messages = array();
w  
Qiang Xue committed
74

Qiang Xue committed
75 76
	private $_levels = 0;

w  
Qiang Xue committed
77
	/**
Qiang Xue committed
78
	 * Exports log [[messages]] to a specific destination.
Qiang Xue committed
79
	 * Child classes must implement this method.
w  
Qiang Xue committed
80
	 */
Qiang Xue committed
81
	abstract public function export();
w  
Qiang Xue committed
82 83

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

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

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

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

Qiang Xue committed
126 127
	/**
	 * @return integer the message levels that this target is interested in. This is a bitmap of
Qiang Xue committed
128
	 * level values. Defaults to 0, meaning  all available levels.
Qiang Xue committed
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 176 177
	 */
	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
178
	/**
w  
Qiang Xue committed
179 180
	 * Filters the given messages according to their categories and levels.
	 * @param array $messages messages to be filtered
Qiang Xue committed
181 182 183 184
	 * @param integer $levels the message levels to filter by. This is a bitmap of
	 * level values. Value 0 means allowing all levels.
	 * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
	 * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
w  
Qiang Xue committed
185
	 * @return array the filtered messages.
w  
Qiang Xue committed
186
	 */
187
	public static function filterMessages($messages, $levels = 0, $categories = array(), $except = array())
w  
Qiang Xue committed
188
	{
w  
Qiang Xue committed
189
		foreach ($messages as $i => $message) {
Qiang Xue committed
190
			if ($levels && !($levels & $message[1])) {
w  
Qiang Xue committed
191 192 193 194
				unset($messages[$i]);
				continue;
			}

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

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

			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
		list($text, $level, $category, $timestamp) = $message;
Qiang Xue committed
229
		$level = Logger::getLevelName($level);
Qiang Xue committed
230 231 232
		if (!is_string($text)) {
			$text = var_export($text, true);
		}
Qiang Xue committed
233 234
		$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
235 236
	}
}