LoggerDataCollector.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\DataCollector;
  11. use Symfony\Component\ErrorHandler\Exception\SilencedErrorContext;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  16. /**
  17. * LogDataCollector.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. *
  21. * @final since Symfony 4.4
  22. */
  23. class LoggerDataCollector extends DataCollector implements LateDataCollectorInterface
  24. {
  25. private $logger;
  26. private $containerPathPrefix;
  27. private $currentRequest;
  28. private $requestStack;
  29. public function __construct($logger = null, string $containerPathPrefix = null, RequestStack $requestStack = null)
  30. {
  31. if (null !== $logger && $logger instanceof DebugLoggerInterface) {
  32. $this->logger = $logger;
  33. }
  34. $this->containerPathPrefix = $containerPathPrefix;
  35. $this->requestStack = $requestStack;
  36. }
  37. /**
  38. * {@inheritdoc}
  39. *
  40. * @param \Throwable|null $exception
  41. */
  42. public function collect(Request $request, Response $response/*, \Throwable $exception = null*/)
  43. {
  44. $this->currentRequest = $this->requestStack && $this->requestStack->getMasterRequest() !== $request ? $request : null;
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function reset()
  50. {
  51. if ($this->logger instanceof DebugLoggerInterface) {
  52. $this->logger->clear();
  53. }
  54. $this->data = [];
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function lateCollect()
  60. {
  61. if (null !== $this->logger) {
  62. $containerDeprecationLogs = $this->getContainerDeprecationLogs();
  63. $this->data = $this->computeErrorsCount($containerDeprecationLogs);
  64. // get compiler logs later (only when they are needed) to improve performance
  65. $this->data['compiler_logs'] = [];
  66. $this->data['compiler_logs_filepath'] = $this->containerPathPrefix.'Compiler.log';
  67. $this->data['logs'] = $this->sanitizeLogs(array_merge($this->logger->getLogs($this->currentRequest), $containerDeprecationLogs));
  68. $this->data = $this->cloneVar($this->data);
  69. }
  70. $this->currentRequest = null;
  71. }
  72. public function getLogs()
  73. {
  74. return isset($this->data['logs']) ? $this->data['logs'] : [];
  75. }
  76. public function getPriorities()
  77. {
  78. return isset($this->data['priorities']) ? $this->data['priorities'] : [];
  79. }
  80. public function countErrors()
  81. {
  82. return isset($this->data['error_count']) ? $this->data['error_count'] : 0;
  83. }
  84. public function countDeprecations()
  85. {
  86. return isset($this->data['deprecation_count']) ? $this->data['deprecation_count'] : 0;
  87. }
  88. public function countWarnings()
  89. {
  90. return isset($this->data['warning_count']) ? $this->data['warning_count'] : 0;
  91. }
  92. public function countScreams()
  93. {
  94. return isset($this->data['scream_count']) ? $this->data['scream_count'] : 0;
  95. }
  96. public function getCompilerLogs()
  97. {
  98. return $this->cloneVar($this->getContainerCompilerLogs($this->data['compiler_logs_filepath'] ?? null));
  99. }
  100. /**
  101. * {@inheritdoc}
  102. */
  103. public function getName()
  104. {
  105. return 'logger';
  106. }
  107. private function getContainerDeprecationLogs(): array
  108. {
  109. if (null === $this->containerPathPrefix || !file_exists($file = $this->containerPathPrefix.'Deprecations.log')) {
  110. return [];
  111. }
  112. if ('' === $logContent = trim(file_get_contents($file))) {
  113. return [];
  114. }
  115. $bootTime = filemtime($file);
  116. $logs = [];
  117. foreach (unserialize($logContent) as $log) {
  118. $log['context'] = ['exception' => new SilencedErrorContext($log['type'], $log['file'], $log['line'], $log['trace'], $log['count'])];
  119. $log['timestamp'] = $bootTime;
  120. $log['priority'] = 100;
  121. $log['priorityName'] = 'DEBUG';
  122. $log['channel'] = null;
  123. $log['scream'] = false;
  124. unset($log['type'], $log['file'], $log['line'], $log['trace'], $log['trace'], $log['count']);
  125. $logs[] = $log;
  126. }
  127. return $logs;
  128. }
  129. private function getContainerCompilerLogs(string $compilerLogsFilepath = null): array
  130. {
  131. if (!file_exists($compilerLogsFilepath)) {
  132. return [];
  133. }
  134. $logs = [];
  135. foreach (file($compilerLogsFilepath, FILE_IGNORE_NEW_LINES) as $log) {
  136. $log = explode(': ', $log, 2);
  137. if (!isset($log[1]) || !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)++$/', $log[0])) {
  138. $log = ['Unknown Compiler Pass', implode(': ', $log)];
  139. }
  140. $logs[$log[0]][] = ['message' => $log[1]];
  141. }
  142. return $logs;
  143. }
  144. private function sanitizeLogs(array $logs)
  145. {
  146. $sanitizedLogs = [];
  147. $silencedLogs = [];
  148. foreach ($logs as $log) {
  149. if (!$this->isSilencedOrDeprecationErrorLog($log)) {
  150. $sanitizedLogs[] = $log;
  151. continue;
  152. }
  153. $message = '_'.$log['message'];
  154. $exception = $log['context']['exception'];
  155. if ($exception instanceof SilencedErrorContext) {
  156. if (isset($silencedLogs[$h = spl_object_hash($exception)])) {
  157. continue;
  158. }
  159. $silencedLogs[$h] = true;
  160. if (!isset($sanitizedLogs[$message])) {
  161. $sanitizedLogs[$message] = $log + [
  162. 'errorCount' => 0,
  163. 'scream' => true,
  164. ];
  165. }
  166. $sanitizedLogs[$message]['errorCount'] += $exception->count;
  167. continue;
  168. }
  169. $errorId = md5("{$exception->getSeverity()}/{$exception->getLine()}/{$exception->getFile()}\0{$message}", true);
  170. if (isset($sanitizedLogs[$errorId])) {
  171. ++$sanitizedLogs[$errorId]['errorCount'];
  172. } else {
  173. $log += [
  174. 'errorCount' => 1,
  175. 'scream' => false,
  176. ];
  177. $sanitizedLogs[$errorId] = $log;
  178. }
  179. }
  180. return array_values($sanitizedLogs);
  181. }
  182. private function isSilencedOrDeprecationErrorLog(array $log): bool
  183. {
  184. if (!isset($log['context']['exception'])) {
  185. return false;
  186. }
  187. $exception = $log['context']['exception'];
  188. if ($exception instanceof SilencedErrorContext) {
  189. return true;
  190. }
  191. if ($exception instanceof \ErrorException && \in_array($exception->getSeverity(), [E_DEPRECATED, E_USER_DEPRECATED], true)) {
  192. return true;
  193. }
  194. return false;
  195. }
  196. private function computeErrorsCount(array $containerDeprecationLogs): array
  197. {
  198. $silencedLogs = [];
  199. $count = [
  200. 'error_count' => $this->logger->countErrors($this->currentRequest),
  201. 'deprecation_count' => 0,
  202. 'warning_count' => 0,
  203. 'scream_count' => 0,
  204. 'priorities' => [],
  205. ];
  206. foreach ($this->logger->getLogs($this->currentRequest) as $log) {
  207. if (isset($count['priorities'][$log['priority']])) {
  208. ++$count['priorities'][$log['priority']]['count'];
  209. } else {
  210. $count['priorities'][$log['priority']] = [
  211. 'count' => 1,
  212. 'name' => $log['priorityName'],
  213. ];
  214. }
  215. if ('WARNING' === $log['priorityName']) {
  216. ++$count['warning_count'];
  217. }
  218. if ($this->isSilencedOrDeprecationErrorLog($log)) {
  219. $exception = $log['context']['exception'];
  220. if ($exception instanceof SilencedErrorContext) {
  221. if (isset($silencedLogs[$h = spl_object_hash($exception)])) {
  222. continue;
  223. }
  224. $silencedLogs[$h] = true;
  225. $count['scream_count'] += $exception->count;
  226. } else {
  227. ++$count['deprecation_count'];
  228. }
  229. }
  230. }
  231. foreach ($containerDeprecationLogs as $deprecationLog) {
  232. $count['deprecation_count'] += $deprecationLog['context']['exception']->count;
  233. }
  234. ksort($count['priorities']);
  235. return $count;
  236. }
  237. }