Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

305 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 an unknown level name is given
  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. $this->_levels = $levels;
  182. }
  183. }
  184. /**
  185. * Filters the given messages according to their categories and levels.
  186. * @param array $messages messages to be filtered.
  187. * The message structure follows that in [[Logger::messages]].
  188. * @param integer $levels the message levels to filter by. This is a bitmap of
  189. * level values. Value 0 means allowing all levels.
  190. * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
  191. * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
  192. * @return array the filtered messages.
  193. */
  194. public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
  195. {
  196. foreach ($messages as $i => $message) {
  197. if ($levels && !($levels & $message[1])) {
  198. unset($messages[$i]);
  199. continue;
  200. }
  201. $matched = empty($categories);
  202. foreach ($categories as $category) {
  203. if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
  204. $matched = true;
  205. break;
  206. }
  207. }
  208. if ($matched) {
  209. foreach ($except as $category) {
  210. $prefix = rtrim($category, '*');
  211. if (($message[2] === $category || $prefix !== $category) && strpos($message[2], $prefix) === 0) {
  212. $matched = false;
  213. break;
  214. }
  215. }
  216. }
  217. if (!$matched) {
  218. unset($messages[$i]);
  219. }
  220. }
  221. return $messages;
  222. }
  223. /**
  224. * Formats a log message for display as a string.
  225. * @param array $message the log message to be formatted.
  226. * The message structure follows that in [[Logger::messages]].
  227. * @return string the formatted message
  228. */
  229. public function formatMessage($message)
  230. {
  231. list($text, $level, $category, $timestamp) = $message;
  232. $level = Logger::getLevelName($level);
  233. if (!is_string($text)) {
  234. // exceptions may not be serializable if in the call stack somewhere is a Closure
  235. if ($text instanceof \Throwable || $text instanceof \Exception) {
  236. $text = (string) $text;
  237. } else {
  238. $text = VarDumper::export($text);
  239. }
  240. }
  241. $traces = [];
  242. if (isset($message[4])) {
  243. foreach ($message[4] as $trace) {
  244. $traces[] = "in {$trace['file']}:{$trace['line']}";
  245. }
  246. }
  247. $prefix = $this->getMessagePrefix($message);
  248. return date('Y-m-d H:i:s', $timestamp) . " {$prefix}[$level][$category] $text"
  249. . (empty($traces) ? '' : "\n " . implode("\n ", $traces));
  250. }
  251. /**
  252. * Returns a string to be prefixed to the given message.
  253. * If [[prefix]] is configured it will return the result of the callback.
  254. * The default implementation will return user IP, user ID and session ID as a prefix.
  255. * @param array $message the message being exported.
  256. * The message structure follows that in [[Logger::messages]].
  257. * @return string the prefix string
  258. */
  259. public function getMessagePrefix($message)
  260. {
  261. if ($this->prefix !== null) {
  262. return call_user_func($this->prefix, $message);
  263. }
  264. if (Yii::$app === null) {
  265. return '';
  266. }
  267. $request = Yii::$app->getRequest();
  268. $ip = $request instanceof Request ? $request->getUserIP() : '-';
  269. /* @var $user \yii\web\User */
  270. $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
  271. if ($user && ($identity = $user->getIdentity(false))) {
  272. $userID = $identity->getId();
  273. } else {
  274. $userID = '-';
  275. }
  276. /* @var $session \yii\web\Session */
  277. $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
  278. $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
  279. return "[$ip][$userID][$sessionID]";
  280. }
  281. }