Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

291 lines
11KB

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