Target.php 8.3 KB

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