You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

311 lines
12KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\log;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\helpers\ArrayHelper;
  12. use yii\helpers\VarDumper;
  13. use yii\web\Request;
  14. /**
  15. * Target is the base class for all log target classes.
  16. *
  17. * A log target object will filter the messages logged by [[Logger]] according
  18. * to its [[levels]] and [[categories]] properties. It may also export the filtered
  19. * messages to specific destination defined by the target, such as emails, files.
  20. *
  21. * Level filter and category filter are combinatorial, i.e., only messages
  22. * satisfying both filter conditions will be handled. Additionally, you
  23. * may specify [[except]] to exclude messages of certain categories.
  24. *
  25. * @property integer $levels The message levels that this target is interested in. This is a bitmap of level
  26. * values. Defaults to 0, meaning all available levels. Note that the type of this property differs in getter
  27. * and setter. See [[getLevels()]] and [[setLevels()]] for details.
  28. *
  29. * @author Qiang Xue <qiang.xue@gmail.com>
  30. * @since 2.0
  31. */
  32. abstract class Target extends Component
  33. {
  34. /**
  35. * @var boolean whether to enable this log target. Defaults to true.
  36. */
  37. public $enabled = true;
  38. /**
  39. * @var array list of message categories that this target is interested in. Defaults to empty, meaning all categories.
  40. * You can use an asterisk at the end of a category so that the category may be used to
  41. * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
  42. * categories starting with 'yii\db\', such as 'yii\db\Connection'.
  43. */
  44. public $categories = [];
  45. /**
  46. * @var array list of message categories that this target is NOT interested in. Defaults to empty, meaning no uninteresting messages.
  47. * If this property is not empty, then any category listed here will be excluded from [[categories]].
  48. * You can use an asterisk at the end of a category so that the category can be used to
  49. * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
  50. * categories starting with 'yii\db\', such as 'yii\db\Connection'.
  51. * @see categories
  52. */
  53. public $except = [];
  54. /**
  55. * @var array list of the PHP predefined variables that should be logged in a message.
  56. * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be logged.
  57. *
  58. * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']`.
  59. *
  60. * Since version 2.0.9 additional syntax can be used:
  61. * Each element could be specified as one of the following:
  62. *
  63. * - `var` - `var` will be logged.
  64. * - `var.key` - only `var[key]` key will be logged.
  65. * - `!var.key` - `var[key]` key will be excluded.
  66. *
  67. * @see \yii\helpers\ArrayHelper::filter()
  68. */
  69. public $logVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER'];
  70. /**
  71. * @var callable a PHP callable that returns a string to be prefixed to every exported message.
  72. *
  73. * If not set, [[getMessagePrefix()]] will be used, which prefixes the message with context information
  74. * such as user IP, user ID and session ID.
  75. *
  76. * The signature of the callable should be `function ($message)`.
  77. */
  78. public $prefix;
  79. /**
  80. * @var integer how many messages should be accumulated before they are exported.
  81. * Defaults to 1000. Note that messages will always be exported when the application terminates.
  82. * Set this property to be 0 if you don't want to export messages until the application terminates.
  83. */
  84. public $exportInterval = 1000;
  85. /**
  86. * @var array the messages that are retrieved from the logger so far by this log target.
  87. * Please refer to [[Logger::messages]] for the details about the message structure.
  88. */
  89. public $messages = [];
  90. private $_levels = 0;
  91. /**
  92. * Exports log [[messages]] to a specific destination.
  93. * Child classes must implement this method.
  94. */
  95. abstract public function export();
  96. /**
  97. * Processes the given log messages.
  98. * This method will filter the given messages with [[levels]] and [[categories]].
  99. * And if requested, it will also export the filtering result to specific medium (e.g. email).
  100. * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
  101. * of each message.
  102. * @param boolean $final whether this method is called at the end of the current application
  103. */
  104. public function collect($messages, $final)
  105. {
  106. $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
  107. $count = count($this->messages);
  108. if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
  109. if (($context = $this->getContextMessage()) !== '') {
  110. $this->messages[] = [$context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME];
  111. }
  112. // set exportInterval to 0 to avoid triggering export again while exporting
  113. $oldExportInterval = $this->exportInterval;
  114. $this->exportInterval = 0;
  115. $this->export();
  116. $this->exportInterval = $oldExportInterval;
  117. $this->messages = [];
  118. }
  119. }
  120. /**
  121. * Generates the context information to be logged.
  122. * The default implementation will dump user information, system variables, etc.
  123. * @return string the context information. If an empty string, it means no context information.
  124. */
  125. protected function getContextMessage()
  126. {
  127. $context = ArrayHelper::filter($GLOBALS, $this->logVars);
  128. $result = [];
  129. foreach ($context as $key => $value) {
  130. $result[] = "\${$key} = " . VarDumper::dumpAsString($value);
  131. }
  132. return implode("\n\n", $result);
  133. }
  134. /**
  135. * @return integer the message levels that this target is interested in. This is a bitmap of
  136. * level values. Defaults to 0, meaning all available levels.
  137. */
  138. public function getLevels()
  139. {
  140. return $this->_levels;
  141. }
  142. /**
  143. * Sets the message levels that this target is interested in.
  144. *
  145. * The parameter can be either an array of interested level names or an integer representing
  146. * the bitmap of the interested level values. Valid level names include: 'error',
  147. * 'warning', 'info', 'trace' and 'profile'; valid level values include:
  148. * [[Logger::LEVEL_ERROR]], [[Logger::LEVEL_WARNING]], [[Logger::LEVEL_INFO]],
  149. * [[Logger::LEVEL_TRACE]] and [[Logger::LEVEL_PROFILE]].
  150. *
  151. * For example,
  152. *
  153. * ```php
  154. * ['error', 'warning']
  155. * // which is equivalent to:
  156. * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING
  157. * ```
  158. *
  159. * @param array|integer $levels message levels that this target is interested in.
  160. * @throws InvalidConfigException if $levels value is not correct.
  161. */
  162. public function setLevels($levels)
  163. {
  164. static $levelMap = [
  165. 'error' => Logger::LEVEL_ERROR,
  166. 'warning' => Logger::LEVEL_WARNING,
  167. 'info' => Logger::LEVEL_INFO,
  168. 'trace' => Logger::LEVEL_TRACE,
  169. 'profile' => Logger::LEVEL_PROFILE,
  170. ];
  171. if (is_array($levels)) {
  172. $this->_levels = 0;
  173. foreach ($levels as $level) {
  174. if (isset($levelMap[$level])) {
  175. $this->_levels |= $levelMap[$level];
  176. } else {
  177. throw new InvalidConfigException("Unrecognized level: $level");
  178. }
  179. }
  180. } else {
  181. $bitmapValues = array_reduce($levelMap, function ($carry, $item) {
  182. return $carry | $item;
  183. });
  184. if (!($bitmapValues & $levels) && $levels !== 0) {
  185. throw new InvalidConfigException("Incorrect $levels value");
  186. }
  187. $this->_levels = $levels;
  188. }
  189. }
  190. /**
  191. * Filters the given messages according to their categories and levels.
  192. * @param array $messages messages to be filtered.
  193. * The message structure follows that in [[Logger::messages]].
  194. * @param integer $levels the message levels to filter by. This is a bitmap of
  195. * level values. Value 0 means allowing all levels.
  196. * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
  197. * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
  198. * @return array the filtered messages.
  199. */
  200. public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
  201. {
  202. foreach ($messages as $i => $message) {
  203. if ($levels && !($levels & $message[1])) {
  204. unset($messages[$i]);
  205. continue;
  206. }
  207. $matched = empty($categories);
  208. foreach ($categories as $category) {
  209. if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
  210. $matched = true;
  211. break;
  212. }
  213. }
  214. if ($matched) {
  215. foreach ($except as $category) {
  216. $prefix = rtrim($category, '*');
  217. if (($message[2] === $category || $prefix !== $category) && strpos($message[2], $prefix) === 0) {
  218. $matched = false;
  219. break;
  220. }
  221. }
  222. }
  223. if (!$matched) {
  224. unset($messages[$i]);
  225. }
  226. }
  227. return $messages;
  228. }
  229. /**
  230. * Formats a log message for display as a string.
  231. * @param array $message the log message to be formatted.
  232. * The message structure follows that in [[Logger::messages]].
  233. * @return string the formatted message
  234. */
  235. public function formatMessage($message)
  236. {
  237. list($text, $level, $category, $timestamp) = $message;
  238. $level = Logger::getLevelName($level);
  239. if (!is_string($text)) {
  240. // exceptions may not be serializable if in the call stack somewhere is a Closure
  241. if ($text instanceof \Throwable || $text instanceof \Exception) {
  242. $text = (string) $text;
  243. } else {
  244. $text = VarDumper::export($text);
  245. }
  246. }
  247. $traces = [];
  248. if (isset($message[4])) {
  249. foreach ($message[4] as $trace) {
  250. $traces[] = "in {$trace['file']}:{$trace['line']}";
  251. }
  252. }
  253. $prefix = $this->getMessagePrefix($message);
  254. return date('Y-m-d H:i:s', $timestamp) . " {$prefix}[$level][$category] $text"
  255. . (empty($traces) ? '' : "\n " . implode("\n ", $traces));
  256. }
  257. /**
  258. * Returns a string to be prefixed to the given message.
  259. * If [[prefix]] is configured it will return the result of the callback.
  260. * The default implementation will return user IP, user ID and session ID as a prefix.
  261. * @param array $message the message being exported.
  262. * The message structure follows that in [[Logger::messages]].
  263. * @return string the prefix string
  264. */
  265. public function getMessagePrefix($message)
  266. {
  267. if ($this->prefix !== null) {
  268. return call_user_func($this->prefix, $message);
  269. }
  270. if (Yii::$app === null) {
  271. return '';
  272. }
  273. $request = Yii::$app->getRequest();
  274. $ip = $request instanceof Request ? $request->getUserIP() : '-';
  275. /* @var $user \yii\web\User */
  276. $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
  277. if ($user && ($identity = $user->getIdentity(false))) {
  278. $userID = $identity->getId();
  279. } else {
  280. $userID = '-';
  281. }
  282. /* @var $session \yii\web\Session */
  283. $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
  284. $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
  285. return "[$ip][$userID][$sessionID]";
  286. }
  287. }