Logger.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. * For more details and usage information on Logger, see the [guide article on logging](guide:runtime-logging).
  25. *
  26. * When the application ends or [[flushInterval]] is reached, Logger will call [[flush()]]
  27. * to send logged messages to different log targets, such as [[FileTarget|file]], [[EmailTarget|email]],
  28. * or [[DbTarget|database]], with the help of the [[dispatcher]].
  29. *
  30. * @property-read array $dbProfiling The first element indicates the number of SQL statements executed, and
  31. * the second element the total time spent in SQL execution. This property is read-only.
  32. * @property-read float $elapsedTime The total elapsed time in seconds for current request. This property is
  33. * read-only.
  34. * @property-read array $profiling The profiling results. Each element is an array consisting of these
  35. * elements: `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`. The `memory`
  36. * and `memoryDiff` values are available since version 2.0.11. This property is read-only.
  37. *
  38. * @author Qiang Xue <qiang.xue@gmail.com>
  39. * @since 2.0
  40. */
  41. class Logger extends Component
  42. {
  43. /**
  44. * Error message level. An error message is one that indicates the abnormal termination of the
  45. * application and may require developer's handling.
  46. */
  47. const LEVEL_ERROR = 0x01;
  48. /**
  49. * Warning message level. A warning message is one that indicates some abnormal happens but
  50. * the application is able to continue to run. Developers should pay attention to this message.
  51. */
  52. const LEVEL_WARNING = 0x02;
  53. /**
  54. * Informational message level. An informational message is one that includes certain information
  55. * for developers to review.
  56. */
  57. const LEVEL_INFO = 0x04;
  58. /**
  59. * Tracing message level. A tracing message is one that reveals the code execution flow.
  60. */
  61. const LEVEL_TRACE = 0x08;
  62. /**
  63. * Profiling message level. This indicates the message is for profiling purpose.
  64. */
  65. const LEVEL_PROFILE = 0x40;
  66. /**
  67. * Profiling message level. This indicates the message is for profiling purpose. It marks the beginning
  68. * of a profiling block.
  69. */
  70. const LEVEL_PROFILE_BEGIN = 0x50;
  71. /**
  72. * Profiling message level. This indicates the message is for profiling purpose. It marks the end
  73. * of a profiling block.
  74. */
  75. const LEVEL_PROFILE_END = 0x60;
  76. /**
  77. * @var array logged messages. This property is managed by [[log()]] and [[flush()]].
  78. * Each log message is of the following structure:
  79. *
  80. * ```
  81. * [
  82. * [0] => message (mixed, can be a string or some complex data, such as an exception object)
  83. * [1] => level (integer)
  84. * [2] => category (string)
  85. * [3] => timestamp (float, obtained by microtime(true))
  86. * [4] => traces (array, debug backtrace, contains the application code call stacks)
  87. * [5] => memory usage in bytes (int, obtained by memory_get_usage()), available since version 2.0.11.
  88. * ]
  89. * ```
  90. */
  91. public $messages = [];
  92. /**
  93. * @var int how many messages should be logged before they are flushed from memory and sent to targets.
  94. * Defaults to 1000, meaning the [[flush()]] method will be invoked once every 1000 messages logged.
  95. * Set this property to be 0 if you don't want to flush messages until the application terminates.
  96. * This property mainly affects how much memory will be taken by the logged messages.
  97. * A smaller value means less memory, but will increase the execution time due to the overhead of [[flush()]].
  98. */
  99. public $flushInterval = 1000;
  100. /**
  101. * @var int how much call stack information (file name and line number) should be logged for each message.
  102. * If it is greater than 0, at most that number of call stacks will be logged. Note that only application
  103. * call stacks are counted.
  104. */
  105. public $traceLevel = 0;
  106. /**
  107. * @var Dispatcher the message dispatcher.
  108. */
  109. public $dispatcher;
  110. /**
  111. * @var array of event names used to get statistical results of DB queries.
  112. * @since 2.0.41
  113. */
  114. public $dbEventNames = ['yii\db\Command::query', 'yii\db\Command::execute'];
  115. /**
  116. * @var bool whether the profiling-aware mode should be switched on.
  117. * If on, [[flush()]] makes sure that profiling blocks are flushed in pairs. In case that any dangling messages are
  118. * detected these are kept for the next flush interval to find their pair. To prevent memory leaks, when number of
  119. * dangling messages reaches flushInterval value, logger flushes them immediately and triggers a warning.
  120. * Keep in mind that profiling-aware mode is more time and memory consuming.
  121. * @since 2.0.43
  122. */
  123. public $profilingAware = false;
  124. /**
  125. * Initializes the logger by registering [[flush()]] as a shutdown function.
  126. */
  127. public function init()
  128. {
  129. parent::init();
  130. register_shutdown_function(function () {
  131. // make regular flush before other shutdown functions, which allows session data collection and so on
  132. $this->flush();
  133. // make sure log entries written by shutdown functions are also flushed
  134. // ensure "flush()" is called last when there are multiple shutdown functions
  135. register_shutdown_function([$this, 'flush'], true);
  136. });
  137. }
  138. /**
  139. * Logs a message with the given type and category.
  140. * If [[traceLevel]] is greater than 0, additional call stack information about
  141. * the application code will be logged as well.
  142. * @param string|array $message the message to be logged. This can be a simple string or a more
  143. * complex data structure that will be handled by a [[Target|log target]].
  144. * @param int $level the level of the message. This must be one of the following:
  145. * `Logger::LEVEL_ERROR`, `Logger::LEVEL_WARNING`, `Logger::LEVEL_INFO`, `Logger::LEVEL_TRACE`, `Logger::LEVEL_PROFILE`,
  146. * `Logger::LEVEL_PROFILE_BEGIN`, `Logger::LEVEL_PROFILE_END`.
  147. * @param string $category the category of the message.
  148. */
  149. public function log($message, $level, $category = 'application')
  150. {
  151. $time = microtime(true);
  152. $traces = [];
  153. if ($this->traceLevel > 0) {
  154. $count = 0;
  155. $ts = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  156. array_pop($ts); // remove the last trace since it would be the entry script, not very useful
  157. foreach ($ts as $trace) {
  158. if (isset($trace['file'], $trace['line']) && strpos($trace['file'], YII2_PATH) !== 0) {
  159. unset($trace['object'], $trace['args']);
  160. $traces[] = $trace;
  161. if (++$count >= $this->traceLevel) {
  162. break;
  163. }
  164. }
  165. }
  166. }
  167. $data = [$message, $level, $category, $time, $traces, memory_get_usage()];
  168. if ($this->profilingAware && in_array($level, [self::LEVEL_PROFILE_BEGIN, self::LEVEL_PROFILE_END])) {
  169. $this->messages[($level == self::LEVEL_PROFILE_BEGIN ? 'begin-' : 'end-') . md5(json_encode($message))] = $data;
  170. } else {
  171. $this->messages[] = $data;
  172. }
  173. if ($this->flushInterval > 0 && count($this->messages) >= $this->flushInterval) {
  174. $this->flush();
  175. }
  176. }
  177. /**
  178. * Flushes log messages from memory to targets.
  179. * @param bool $final whether this is a final call during a request.
  180. */
  181. public function flush($final = false)
  182. {
  183. if ($this->profilingAware) {
  184. $keep = [];
  185. $messages = [];
  186. foreach ($this->messages as $index => $message) {
  187. if (is_int($index)) {
  188. $messages[] = $message;
  189. } else {
  190. if (strpos($index, 'begin-') === 0) {
  191. $oppositeProfile = 'end-' . substr($index, 6);
  192. } else {
  193. $oppositeProfile = 'begin-' . substr($index, 4);
  194. }
  195. if (array_key_exists($oppositeProfile, $this->messages)) {
  196. $messages[] = $message;
  197. } else {
  198. $keep[$index] = $message;
  199. }
  200. }
  201. }
  202. if ($this->flushInterval > 0 && count($keep) >= $this->flushInterval) {
  203. $this->messages = [];
  204. $this->log(
  205. 'Number of dangling profiling block messages reached flushInterval value and therefore these were flushed. Please consider setting higher flushInterval value or making profiling blocks shorter.',
  206. self::LEVEL_WARNING
  207. );
  208. $messages = array_merge($messages, array_values($keep));
  209. } else {
  210. $this->messages = $keep;
  211. }
  212. } else {
  213. $messages = $this->messages;
  214. $this->messages = [];
  215. }
  216. if ($this->dispatcher instanceof Dispatcher) {
  217. $this->dispatcher->dispatch($messages, $final);
  218. }
  219. }
  220. /**
  221. * Returns the total elapsed time since the start of the current request.
  222. * This method calculates the difference between now and the timestamp
  223. * defined by constant `YII_BEGIN_TIME` which is evaluated at the beginning
  224. * of [[\yii\BaseYii]] class file.
  225. * @return float the total elapsed time in seconds for current request.
  226. */
  227. public function getElapsedTime()
  228. {
  229. return microtime(true) - YII_BEGIN_TIME;
  230. }
  231. /**
  232. * Returns the profiling results.
  233. *
  234. * By default, all profiling results will be returned. You may provide
  235. * `$categories` and `$excludeCategories` as parameters to retrieve the
  236. * results that you are interested in.
  237. *
  238. * @param array $categories list of categories that you are interested in.
  239. * You can use an asterisk at the end of a category to do a prefix match.
  240. * For example, 'yii\db\*' will match categories starting with 'yii\db\',
  241. * such as 'yii\db\Connection'.
  242. * @param array $excludeCategories list of categories that you want to exclude
  243. * @return array the profiling results. Each element is an array consisting of these elements:
  244. * `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`.
  245. * The `memory` and `memoryDiff` values are available since version 2.0.11.
  246. */
  247. public function getProfiling($categories = [], $excludeCategories = [])
  248. {
  249. $timings = $this->calculateTimings($this->messages);
  250. if (empty($categories) && empty($excludeCategories)) {
  251. return $timings;
  252. }
  253. foreach ($timings as $outerIndex => $outerTimingItem) {
  254. $currentIndex = $outerIndex;
  255. $matched = empty($categories);
  256. foreach ($categories as $category) {
  257. $prefix = rtrim($category, '*');
  258. if (
  259. ($outerTimingItem['category'] === $category || $prefix !== $category)
  260. && strpos($outerTimingItem['category'], $prefix) === 0
  261. ) {
  262. $matched = true;
  263. break;
  264. }
  265. }
  266. if ($matched) {
  267. foreach ($excludeCategories as $category) {
  268. $prefix = rtrim($category, '*');
  269. foreach ($timings as $innerIndex => $innerTimingItem) {
  270. $currentIndex = $innerIndex;
  271. if (
  272. ($innerTimingItem['category'] === $category || $prefix !== $category)
  273. && strpos($innerTimingItem['category'], $prefix) === 0
  274. ) {
  275. $matched = false;
  276. break;
  277. }
  278. }
  279. }
  280. }
  281. if (!$matched) {
  282. unset($timings[$currentIndex]);
  283. }
  284. }
  285. return array_values($timings);
  286. }
  287. /**
  288. * Returns the statistical results of DB queries.
  289. * The results returned include the number of SQL statements executed and
  290. * the total time spent.
  291. * @return array the first element indicates the number of SQL statements executed,
  292. * and the second element the total time spent in SQL execution.
  293. */
  294. public function getDbProfiling()
  295. {
  296. $timings = $this->getProfiling($this->dbEventNames);
  297. $count = count($timings);
  298. $time = 0;
  299. foreach ($timings as $timing) {
  300. $time += $timing['duration'];
  301. }
  302. return [$count, $time];
  303. }
  304. /**
  305. * Calculates the elapsed time for the given log messages.
  306. * @param array $messages the log messages obtained from profiling
  307. * @return array timings. Each element is an array consisting of these elements:
  308. * `info`, `category`, `timestamp`, `trace`, `level`, `duration`, `memory`, `memoryDiff`.
  309. * The `memory` and `memoryDiff` values are available since version 2.0.11.
  310. */
  311. public function calculateTimings($messages)
  312. {
  313. $timings = [];
  314. $stack = [];
  315. foreach ($messages as $i => $log) {
  316. list($token, $level, $category, $timestamp, $traces) = $log;
  317. $memory = isset($log[5]) ? $log[5] : 0;
  318. $log[6] = $i;
  319. $hash = md5(json_encode($token));
  320. if ($level == self::LEVEL_PROFILE_BEGIN) {
  321. $stack[$hash] = $log;
  322. } elseif ($level == self::LEVEL_PROFILE_END) {
  323. if (isset($stack[$hash])) {
  324. $timings[$stack[$hash][6]] = [
  325. 'info' => $stack[$hash][0],
  326. 'category' => $stack[$hash][2],
  327. 'timestamp' => $stack[$hash][3],
  328. 'trace' => $stack[$hash][4],
  329. 'level' => count($stack) - 1,
  330. 'duration' => $timestamp - $stack[$hash][3],
  331. 'memory' => $memory,
  332. 'memoryDiff' => $memory - (isset($stack[$hash][5]) ? $stack[$hash][5] : 0),
  333. ];
  334. unset($stack[$hash]);
  335. }
  336. }
  337. }
  338. ksort($timings);
  339. return array_values($timings);
  340. }
  341. /**
  342. * Returns the text display of the specified level.
  343. * @param int $level the message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]].
  344. * @return string the text display of the level
  345. */
  346. public static function getLevelName($level)
  347. {
  348. static $levels = [
  349. self::LEVEL_ERROR => 'error',
  350. self::LEVEL_WARNING => 'warning',
  351. self::LEVEL_INFO => 'info',
  352. self::LEVEL_TRACE => 'trace',
  353. self::LEVEL_PROFILE_BEGIN => 'profile begin',
  354. self::LEVEL_PROFILE_END => 'profile end',
  355. self::LEVEL_PROFILE => 'profile',
  356. ];
  357. return isset($levels[$level]) ? $levels[$level] : 'unknown';
  358. }
  359. }