Target.php 12 KB

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