Target.php 8.32 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
 *
25
 * @property integer $levels The message levels that this target is interested in. This is a bitmap of level
26 27
 * values. Defaults to 0, meaning  all available levels. Note that the type of this property differs in getter
 * and setter. See [[getLevels()]] and [[setLevels()]] for details.
Qiang Xue committed
28
 *
w  
Qiang Xue committed
29 30 31
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
32
abstract class Target extends Component
w  
Qiang Xue committed
33 34 35 36 37
{
	/**
	 * @var boolean whether to enable this log target. Defaults to true.
	 */
	public $enabled = true;
w  
Qiang Xue committed
38 39 40 41
	/**
	 * @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
42
	 * categories starting with 'yii\db\', such as 'yii\db\Connection'.
w  
Qiang Xue committed
43
	 */
Alexander Makarov committed
44
	public $categories = [];
w  
Qiang Xue committed
45 46 47 48 49
	/**
	 * @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
50
	 * categories starting with 'yii\db\', such as 'yii\db\Connection'.
w  
Qiang Xue committed
51 52
	 * @see categories
	 */
Alexander Makarov committed
53
	public $except = [];
w  
Qiang Xue committed
54
	/**
Qiang Xue committed
55
	 * @var boolean whether to log a message containing the current user name and ID. Defaults to false.
w  
Qiang Xue committed
56
	 * @see \yii\web\User
w  
Qiang Xue committed
57
	 */
w  
Qiang Xue committed
58
	public $logUser = false;
w  
Qiang Xue committed
59
	/**
w  
Qiang Xue committed
60 61
	 * @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.
Alexander Makarov committed
62
	 * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']`.
w  
Qiang Xue committed
63
	 */
Alexander Makarov committed
64
	public $logVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER'];
Qiang Xue committed
65
	/**
Qiang Xue committed
66 67 68
	 * @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
69
	 */
Qiang Xue committed
70
	public $exportInterval = 1000;
w  
Qiang Xue committed
71
	/**
w  
Qiang Xue committed
72
	 * @var array the messages that are retrieved from the logger so far by this log target.
Qiang Xue committed
73
	 * Please refer to [[Logger::messages]] for the details about the message structure.
w  
Qiang Xue committed
74
	 */
Alexander Makarov committed
75
	public $messages = [];
w  
Qiang Xue committed
76

Qiang Xue committed
77 78
	private $_levels = 0;

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

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

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

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

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

Qiang Xue committed
128 129
	/**
	 * @return integer the message levels that this target is interested in. This is a bitmap of
Qiang Xue committed
130
	 * level values. Defaults to 0, meaning  all available levels.
Qiang Xue committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
	 */
	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,
	 *
	 * ~~~
Alexander Makarov committed
149
	 * ['error', 'warning']
Qiang Xue committed
150 151 152 153 154 155 156 157 158
	 * // 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)
	{
Alexander Makarov committed
159
		static $levelMap = [
Qiang Xue committed
160 161 162 163 164
			'error' => Logger::LEVEL_ERROR,
			'warning' => Logger::LEVEL_WARNING,
			'info' => Logger::LEVEL_INFO,
			'trace' => Logger::LEVEL_TRACE,
			'profile' => Logger::LEVEL_PROFILE,
Alexander Makarov committed
165
		];
Qiang Xue committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179
		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
180
	/**
w  
Qiang Xue committed
181 182
	 * Filters the given messages according to their categories and levels.
	 * @param array $messages messages to be filtered
Qiang Xue committed
183 184 185 186
	 * @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
187
	 * @return array the filtered messages.
w  
Qiang Xue committed
188
	 */
Alexander Makarov committed
189
	public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
w  
Qiang Xue committed
190
	{
w  
Qiang Xue committed
191
		foreach ($messages as $i => $message) {
Qiang Xue committed
192
			if ($levels && !($levels & $message[1])) {
w  
Qiang Xue committed
193 194 195 196
				unset($messages[$i]);
				continue;
			}

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

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

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

	/**
w  
Qiang Xue committed
223 224 225 226
	 * 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
227
	 */
w  
Qiang Xue committed
228
	public function formatMessage($message)
w  
Qiang Xue committed
229
	{
Qiang Xue committed
230
		list($text, $level, $category, $timestamp) = $message;
Qiang Xue committed
231
		$level = Logger::getLevelName($level);
Qiang Xue committed
232 233 234
		if (!is_string($text)) {
			$text = var_export($text, true);
		}
Qiang Xue committed
235
		$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
236
		return date('Y/m/d H:i:s', $timestamp) . " [$ip] [$level] [$category] $text";
w  
Qiang Xue committed
237 238
	}
}