Target.php 14 KB

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