You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

312 lines
12KB

  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. /**
  11. * Logger records logged messages in memory and sends them to different targets if [[dispatcher]] is set.
  12. *
  13. * A Logger instance can be accessed via `Yii::getLogger()`. You can call the method [[log()]] to record a single log message.
  14. * For convenience, a set of shortcut methods are provided for logging messages of various severity levels
  15. * via the [[Yii]] class:
  16. *
  17. * - [[Yii::trace()]]
  18. * - [[Yii::error()]]
  19. * - [[Yii::warning()]]
  20. * - [[Yii::info()]]
  21. * - [[Yii::beginProfile()]]
  22. * - [[Yii::endProfile()]]
  23. *
  24. * When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]]
  25. * to send logged messages to different log targets, such as [[FileTarget|file]], [[EmailTarget|email]],
  26. * or [[DbTarget|database]], with the help of the [[dispatcher]].
  27. *
  28. * @property array $dbProfiling The first element indicates the number of SQL statements executed, and the
  29. * second element the total time spent in SQL execution. This property is read-only.
  30. * @property float $elapsedTime The total elapsed time in seconds for current request. This property is
  31. * read-only.
  32. * @property array $profiling The profiling results. Each element is an array consisting of these elements:
  33. * `info`, `category`, `timestamp`, `trace`, `level`, `duration`. This property is read-only.
  34. *
  35. * @author Qiang Xue <qiang.xue@gmail.com>
  36. * @since 2.0
  37. */
  38. class Logger extends Component
  39. {
  40. /**
  41. * Error message level. An error message is one that indicates the abnormal termination of the
  42. * application and may require developer's handling.
  43. */
  44. const LEVEL_ERROR = 0x01;
  45. /**
  46. * Warning message level. A warning message is one that indicates some abnormal happens but
  47. * the application is able to continue to run. Developers should pay attention to this message.
  48. */
  49. const LEVEL_WARNING = 0x02;
  50. /**
  51. * Informational message level. An informational message is one that includes certain information
  52. * for developers to review.
  53. */
  54. const LEVEL_INFO = 0x04;
  55. /**
  56. * Tracing message level. An tracing message is one that reveals the code execution flow.
  57. */
  58. const LEVEL_TRACE = 0x08;
  59. /**
  60. * Profiling message level. This indicates the message is for profiling purpose.
  61. */
  62. const LEVEL_PROFILE = 0x40;
  63. /**
  64. * Profiling message level. This indicates the message is for profiling purpose. It marks the
  65. * beginning of a profiling block.
  66. */
  67. const LEVEL_PROFILE_BEGIN = 0x50;
  68. /**
  69. * Profiling message level. This indicates the message is for profiling purpose. It marks the
  70. * end of a profiling block.
  71. */
  72. const LEVEL_PROFILE_END = 0x60;
  73. /**
  74. * @var array logged messages. This property is managed by [[log()]] and [[flush()]].
  75. * Each log message is of the following structure:
  76. *
  77. * ~~~
  78. * [
  79. * [0] => message (mixed, can be a string or some complex data, such as an exception object)
  80. * [1] => level (integer)
  81. * [2] => category (string)
  82. * [3] => timestamp (float, obtained by microtime(true))
  83. * [4] => traces (array, debug backtrace, contains the application code call stacks)
  84. * ]
  85. * ~~~
  86. */
  87. public $messages = [];
  88. /**
  89. * @var integer how many messages should be logged before they are flushed from memory and sent to targets.
  90. * Defaults to 1000, meaning the [[flush]] method will be invoked once every 1000 messages logged.
  91. * Set this property to be 0 if you don't want to flush messages until the application terminates.
  92. * This property mainly affects how much memory will be taken by the logged messages.
  93. * A smaller value means less memory, but will increase the execution time due to the overhead of [[flush()]].
  94. */
  95. public $flushInterval = 1000;
  96. /**
  97. * @var integer how much call stack information (file name and line number) should be logged for each message.
  98. * If it is greater than 0, at most that number of call stacks will be logged. Note that only application
  99. * call stacks are counted.
  100. */
  101. public $traceLevel = 0;
  102. /**
  103. * @var Dispatcher the message dispatcher
  104. */
  105. public $dispatcher;
  106. /**
  107. * Initializes the logger by registering [[flush()]] as a shutdown function.
  108. */
  109. public function init()
  110. {
  111. parent::init();
  112. register_shutdown_function(function () {
  113. // make sure "flush()" is called last when there are multiple shutdown functions
  114. register_shutdown_function([$this, 'flush'], true);
  115. });
  116. }
  117. /**
  118. * Logs a message with the given type and category.
  119. * If [[traceLevel]] is greater than 0, additional call stack information about
  120. * the application code will be logged as well.
  121. * @param string|array $message the message to be logged. This can be a simple string or a more
  122. * complex data structure that will be handled by a [[Target|log target]].
  123. * @param integer $level the level of the message. This must be one of the following:
  124. * `Logger::LEVEL_ERROR`, `Logger::LEVEL_WARNING`, `Logger::LEVEL_INFO`, `Logger::LEVEL_TRACE`,
  125. * `Logger::LEVEL_PROFILE_BEGIN`, `Logger::LEVEL_PROFILE_END`.
  126. * @param string $category the category of the message.
  127. */
  128. public function log($message, $level, $category = 'application')
  129. {
  130. $time = microtime(true);
  131. $traces = [];
  132. if ($this->traceLevel > 0) {
  133. $count = 0;
  134. $ts = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  135. array_pop($ts); // remove the last trace since it would be the entry script, not very useful
  136. foreach ($ts as $trace) {
  137. if (isset($trace['file'], $trace['line']) && strpos($trace['file'], YII2_PATH) !== 0) {
  138. unset($trace['object'], $trace['args']);
  139. $traces[] = $trace;
  140. if (++$count >= $this->traceLevel) {
  141. break;
  142. }
  143. }
  144. }
  145. }
  146. $this->messages[] = [$message, $level, $category, $time, $traces];
  147. if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
  148. $this->flush();
  149. }
  150. }
  151. /**
  152. * Flushes log messages from memory to targets.
  153. * @param boolean $final whether this is a final call during a request.
  154. */
  155. public function flush($final = false)
  156. {
  157. $messages = $this->messages;
  158. // https://github.com/yiisoft/yii2/issues/5619
  159. // new messages could be logged while the existing ones are being handled by targets
  160. $this->messages = [];
  161. if ($this->dispatcher instanceof Dispatcher) {
  162. $this->dispatcher->dispatch($messages, $final);
  163. }
  164. }
  165. /**
  166. * Returns the total elapsed time since the start of the current request.
  167. * This method calculates the difference between now and the timestamp
  168. * defined by constant `YII_BEGIN_TIME` which is evaluated at the beginning
  169. * of [[\yii\BaseYii]] class file.
  170. * @return float the total elapsed time in seconds for current request.
  171. */
  172. public function getElapsedTime()
  173. {
  174. return microtime(true) - YII_BEGIN_TIME;
  175. }
  176. /**
  177. * Returns the profiling results.
  178. *
  179. * By default, all profiling results will be returned. You may provide
  180. * `$categories` and `$excludeCategories` as parameters to retrieve the
  181. * results that you are interested in.
  182. *
  183. * @param array $categories list of categories that you are interested in.
  184. * You can use an asterisk at the end of a category to do a prefix match.
  185. * For example, 'yii\db\*' will match categories starting with 'yii\db\',
  186. * such as 'yii\db\Connection'.
  187. * @param array $excludeCategories list of categories that you want to exclude
  188. * @return array the profiling results. Each element is an array consisting of these elements:
  189. * `info`, `category`, `timestamp`, `trace`, `level`, `duration`.
  190. */
  191. public function getProfiling($categories = [], $excludeCategories = [])
  192. {
  193. $timings = $this->calculateTimings($this->messages);
  194. if (empty($categories) && empty($excludeCategories)) {
  195. return $timings;
  196. }
  197. foreach ($timings as $i => $timing) {
  198. $matched = empty($categories);
  199. foreach ($categories as $category) {
  200. $prefix = rtrim($category, '*');
  201. if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) {
  202. $matched = true;
  203. break;
  204. }
  205. }
  206. if ($matched) {
  207. foreach ($excludeCategories as $category) {
  208. $prefix = rtrim($category, '*');
  209. foreach ($timings as $i => $timing) {
  210. if (($timing['category'] === $category || $prefix !== $category) && strpos($timing['category'], $prefix) === 0) {
  211. $matched = false;
  212. break;
  213. }
  214. }
  215. }
  216. }
  217. if (!$matched) {
  218. unset($timings[$i]);
  219. }
  220. }
  221. return array_values($timings);
  222. }
  223. /**
  224. * Returns the statistical results of DB queries.
  225. * The results returned include the number of SQL statements executed and
  226. * the total time spent.
  227. * @return array the first element indicates the number of SQL statements executed,
  228. * and the second element the total time spent in SQL execution.
  229. */
  230. public function getDbProfiling()
  231. {
  232. $timings = $this->getProfiling(['yii\db\Command::query', 'yii\db\Command::execute']);
  233. $count = count($timings);
  234. $time = 0;
  235. foreach ($timings as $timing) {
  236. $time += $timing['duration'];
  237. }
  238. return [$count, $time];
  239. }
  240. /**
  241. * Calculates the elapsed time for the given log messages.
  242. * @param array $messages the log messages obtained from profiling
  243. * @return array timings. Each element is an array consisting of these elements:
  244. * `info`, `category`, `timestamp`, `trace`, `level`, `duration`.
  245. */
  246. public function calculateTimings($messages)
  247. {
  248. $timings = [];
  249. $stack = [];
  250. foreach ($messages as $i => $log) {
  251. list($token, $level, $category, $timestamp, $traces) = $log;
  252. $log[5] = $i;
  253. if ($level == Logger::LEVEL_PROFILE_BEGIN) {
  254. $stack[] = $log;
  255. } elseif ($level == Logger::LEVEL_PROFILE_END) {
  256. if (($last = array_pop($stack)) !== null && $last[0] === $token) {
  257. $timings[$last[5]] = [
  258. 'info' => $last[0],
  259. 'category' => $last[2],
  260. 'timestamp' => $last[3],
  261. 'trace' => $last[4],
  262. 'level' => count($stack),
  263. 'duration' => $timestamp - $last[3],
  264. ];
  265. }
  266. }
  267. }
  268. ksort($timings);
  269. return array_values($timings);
  270. }
  271. /**
  272. * Returns the text display of the specified level.
  273. * @param integer $level the message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]].
  274. * @return string the text display of the level
  275. */
  276. public static function getLevelName($level)
  277. {
  278. static $levels = [
  279. self::LEVEL_ERROR => 'error',
  280. self::LEVEL_WARNING => 'warning',
  281. self::LEVEL_INFO => 'info',
  282. self::LEVEL_TRACE => 'trace',
  283. self::LEVEL_PROFILE_BEGIN => 'profile begin',
  284. self::LEVEL_PROFILE_END => 'profile end',
  285. ];
  286. return isset($levels[$level]) ? $levels[$level] : 'unknown';
  287. }
  288. }