Target.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 and
  30. * 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 = [
  74. '_GET',
  75. '_POST',
  76. '_FILES',
  77. '_COOKIE',
  78. '_SESSION',
  79. '_SERVER',
  80. ];
  81. /**
  82. * @var array list of the PHP predefined variables that should NOT be logged "as is" and should always be replaced
  83. * with a mask `***` before logging, when exist.
  84. *
  85. * Defaults to `[ '_SERVER.HTTP_AUTHORIZATION', '_SERVER.PHP_AUTH_USER', '_SERVER.PHP_AUTH_PW']`
  86. *
  87. * Each element could be specified as one of the following:
  88. *
  89. * - `var` - `var` will be logged as `***`
  90. * - `var.key` - only `var[key]` will be logged as `***`
  91. *
  92. * @since 2.0.16
  93. */
  94. public $maskVars = [
  95. '_SERVER.HTTP_AUTHORIZATION',
  96. '_SERVER.PHP_AUTH_USER',
  97. '_SERVER.PHP_AUTH_PW',
  98. ];
  99. /**
  100. * @var callable a PHP callable that returns a string to be prefixed to every exported message.
  101. *
  102. * If not set, [[getMessagePrefix()]] will be used, which prefixes the message with context information
  103. * such as user IP, user ID and session ID.
  104. *
  105. * The signature of the callable should be `function ($message)`.
  106. */
  107. public $prefix;
  108. /**
  109. * @var int how many messages should be accumulated before they are exported.
  110. * Defaults to 1000. Note that messages will always be exported when the application terminates.
  111. * Set this property to be 0 if you don't want to export messages until the application terminates.
  112. */
  113. public $exportInterval = 1000;
  114. /**
  115. * @var array the messages that are retrieved from the logger so far by this log target.
  116. * Please refer to [[Logger::messages]] for the details about the message structure.
  117. */
  118. public $messages = [];
  119. /**
  120. * @var bool whether to log time with microseconds.
  121. * Defaults to false.
  122. * @since 2.0.13
  123. */
  124. public $microtime = false;
  125. private $_levels = 0;
  126. private $_enabled = true;
  127. /**
  128. * Exports log [[messages]] to a specific destination.
  129. * Child classes must implement this method.
  130. */
  131. abstract public function export();
  132. /**
  133. * Processes the given log messages.
  134. * This method will filter the given messages with [[levels]] and [[categories]].
  135. * And if requested, it will also export the filtering result to specific medium (e.g. email).
  136. * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
  137. * of each message.
  138. * @param bool $final whether this method is called at the end of the current application
  139. */
  140. public function collect($messages, $final)
  141. {
  142. $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
  143. $count = count($this->messages);
  144. if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
  145. if (($context = $this->getContextMessage()) !== '') {
  146. $this->messages[] = [$context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME, [], 0];
  147. }
  148. // set exportInterval to 0 to avoid triggering export again while exporting
  149. $oldExportInterval = $this->exportInterval;
  150. $this->exportInterval = 0;
  151. $this->export();
  152. $this->exportInterval = $oldExportInterval;
  153. $this->messages = [];
  154. }
  155. }
  156. /**
  157. * Generates the context information to be logged.
  158. * The default implementation will dump user information, system variables, etc.
  159. * @return string the context information. If an empty string, it means no context information.
  160. */
  161. protected function getContextMessage()
  162. {
  163. $context = ArrayHelper::filter($GLOBALS, $this->logVars);
  164. foreach ($this->maskVars as $var) {
  165. if (ArrayHelper::getValue($context, $var) !== null) {
  166. ArrayHelper::setValue($context, $var, '***');
  167. }
  168. }
  169. $result = [];
  170. foreach ($context as $key => $value) {
  171. $result[] = "\${$key} = " . VarDumper::dumpAsString($value);
  172. }
  173. return implode("\n\n", $result);
  174. }
  175. /**
  176. * @return int the message levels that this target is interested in. This is a bitmap of
  177. * level values. Defaults to 0, meaning all available levels.
  178. */
  179. public function getLevels()
  180. {
  181. return $this->_levels;
  182. }
  183. /**
  184. * Sets the message levels that this target is interested in.
  185. *
  186. * The parameter can be either an array of interested level names or an integer representing
  187. * the bitmap of the interested level values. Valid level names include: 'error',
  188. * 'warning', 'info', 'trace' and 'profile'; valid level values include:
  189. * [[Logger::LEVEL_ERROR]], [[Logger::LEVEL_WARNING]], [[Logger::LEVEL_INFO]],
  190. * [[Logger::LEVEL_TRACE]] and [[Logger::LEVEL_PROFILE]].
  191. *
  192. * For example,
  193. *
  194. * ```php
  195. * ['error', 'warning']
  196. * // which is equivalent to:
  197. * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING
  198. * ```
  199. *
  200. * @param array|int $levels message levels that this target is interested in.
  201. * @throws InvalidConfigException if $levels value is not correct.
  202. */
  203. public function setLevels($levels)
  204. {
  205. static $levelMap = [
  206. 'error' => Logger::LEVEL_ERROR,
  207. 'warning' => Logger::LEVEL_WARNING,
  208. 'info' => Logger::LEVEL_INFO,
  209. 'trace' => Logger::LEVEL_TRACE,
  210. 'profile' => Logger::LEVEL_PROFILE,
  211. ];
  212. if (is_array($levels)) {
  213. $this->_levels = 0;
  214. foreach ($levels as $level) {
  215. if (isset($levelMap[$level])) {
  216. $this->_levels |= $levelMap[$level];
  217. } else {
  218. throw new InvalidConfigException("Unrecognized level: $level");
  219. }
  220. }
  221. } else {
  222. $bitmapValues = array_reduce($levelMap, function ($carry, $item) {
  223. return $carry | $item;
  224. });
  225. if (!($bitmapValues & $levels) && $levels !== 0) {
  226. throw new InvalidConfigException("Incorrect $levels value");
  227. }
  228. $this->_levels = $levels;
  229. }
  230. }
  231. /**
  232. * Filters the given messages according to their categories and levels.
  233. * @param array $messages messages to be filtered.
  234. * The message structure follows that in [[Logger::messages]].
  235. * @param int $levels the message levels to filter by. This is a bitmap of
  236. * level values. Value 0 means allowing all levels.
  237. * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
  238. * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
  239. * @return array the filtered messages.
  240. */
  241. public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
  242. {
  243. foreach ($messages as $i => $message) {
  244. if ($levels && !($levels & $message[1])) {
  245. unset($messages[$i]);
  246. continue;
  247. }
  248. $matched = empty($categories);
  249. foreach ($categories as $category) {
  250. if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
  251. $matched = true;
  252. break;
  253. }
  254. }
  255. if ($matched) {
  256. foreach ($except as $category) {
  257. $prefix = rtrim($category, '*');
  258. if (($message[2] === $category || $prefix !== $category) && strpos($message[2], $prefix) === 0) {
  259. $matched = false;
  260. break;
  261. }
  262. }
  263. }
  264. if (!$matched) {
  265. unset($messages[$i]);
  266. }
  267. }
  268. return $messages;
  269. }
  270. /**
  271. * Formats a log message for display as a string.
  272. * @param array $message the log message to be formatted.
  273. * The message structure follows that in [[Logger::messages]].
  274. * @return string the formatted message
  275. */
  276. public function formatMessage($message)
  277. {
  278. list($text, $level, $category, $timestamp) = $message;
  279. $level = Logger::getLevelName($level);
  280. if (!is_string($text)) {
  281. // exceptions may not be serializable if in the call stack somewhere is a Closure
  282. if ($text instanceof \Throwable || $text instanceof \Exception) {
  283. $text = (string) $text;
  284. } else {
  285. $text = VarDumper::export($text);
  286. }
  287. }
  288. $traces = [];
  289. if (isset($message[4])) {
  290. foreach ($message[4] as $trace) {
  291. $traces[] = "in {$trace['file']}:{$trace['line']}";
  292. }
  293. }
  294. $prefix = $this->getMessagePrefix($message);
  295. return $this->getTime($timestamp) . " {$prefix}[$level][$category] $text"
  296. . (empty($traces) ? '' : "\n " . implode("\n ", $traces));
  297. }
  298. /**
  299. * Returns a string to be prefixed to the given message.
  300. * If [[prefix]] is configured it will return the result of the callback.
  301. * The default implementation will return user IP, user ID and session ID as a prefix.
  302. * @param array $message the message being exported.
  303. * The message structure follows that in [[Logger::messages]].
  304. * @return string the prefix string
  305. */
  306. public function getMessagePrefix($message)
  307. {
  308. if ($this->prefix !== null) {
  309. return call_user_func($this->prefix, $message);
  310. }
  311. if (Yii::$app === null) {
  312. return '';
  313. }
  314. $request = Yii::$app->getRequest();
  315. $ip = $request instanceof Request ? $request->getUserIP() : '-';
  316. /* @var $user \yii\web\User */
  317. $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
  318. if ($user && ($identity = $user->getIdentity(false))) {
  319. $userID = $identity->getId();
  320. } else {
  321. $userID = '-';
  322. }
  323. /* @var $session \yii\web\Session */
  324. $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
  325. $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
  326. return "[$ip][$userID][$sessionID]";
  327. }
  328. /**
  329. * Sets a value indicating whether this log target is enabled.
  330. * @param bool|callable $value a boolean value or a callable to obtain the value from.
  331. * The callable value is available since version 2.0.13.
  332. *
  333. * A callable may be used to determine whether the log target should be enabled in a dynamic way.
  334. * For example, to only enable a log if the current user is logged in you can configure the target
  335. * as follows:
  336. *
  337. * ```php
  338. * 'enabled' => function() {
  339. * return !Yii::$app->user->isGuest;
  340. * }
  341. * ```
  342. */
  343. public function setEnabled($value)
  344. {
  345. $this->_enabled = $value;
  346. }
  347. /**
  348. * Check whether the log target is enabled.
  349. * @property bool Indicates whether this log target is enabled. Defaults to true.
  350. * @return bool A value indicating whether this log target is enabled.
  351. */
  352. public function getEnabled()
  353. {
  354. if (is_callable($this->_enabled)) {
  355. return call_user_func($this->_enabled, $this);
  356. }
  357. return $this->_enabled;
  358. }
  359. /**
  360. * Returns formatted ('Y-m-d H:i:s') timestamp for message.
  361. * If [[microtime]] is configured to true it will return format 'Y-m-d H:i:s.u'.
  362. * @param float $timestamp
  363. * @return string
  364. * @since 2.0.13
  365. */
  366. protected function getTime($timestamp)
  367. {
  368. $parts = explode('.', sprintf('%F', $timestamp));
  369. return date('Y-m-d H:i:s', $parts[0]) . ($this->microtime ? ('.' . $parts[1]) : '');
  370. }
  371. }