DebugProcessor.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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\Bridge\Monolog\Processor;
  11. use Monolog\Logger;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  15. use Symfony\Contracts\Service\ResetInterface;
  16. class DebugProcessor implements DebugLoggerInterface, ResetInterface
  17. {
  18. private $records = [];
  19. private $errorCount = [];
  20. private $requestStack;
  21. public function __construct(RequestStack $requestStack = null)
  22. {
  23. $this->requestStack = $requestStack;
  24. }
  25. public function __invoke(array $record)
  26. {
  27. $hash = $this->requestStack && ($request = $this->requestStack->getCurrentRequest()) ? spl_object_hash($request) : '';
  28. $this->records[$hash][] = [
  29. 'timestamp' => $record['datetime'] instanceof \DateTimeInterface ? $record['datetime']->getTimestamp() : strtotime($record['datetime']),
  30. 'message' => $record['message'],
  31. 'priority' => $record['level'],
  32. 'priorityName' => $record['level_name'],
  33. 'context' => $record['context'],
  34. 'channel' => $record['channel'] ?? '',
  35. ];
  36. if (!isset($this->errorCount[$hash])) {
  37. $this->errorCount[$hash] = 0;
  38. }
  39. switch ($record['level']) {
  40. case Logger::ERROR:
  41. case Logger::CRITICAL:
  42. case Logger::ALERT:
  43. case Logger::EMERGENCY:
  44. ++$this->errorCount[$hash];
  45. }
  46. return $record;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function getLogs(Request $request = null)
  52. {
  53. if (null !== $request) {
  54. return $this->records[spl_object_hash($request)] ?? [];
  55. }
  56. if (0 === \count($this->records)) {
  57. return [];
  58. }
  59. return array_merge(...array_values($this->records));
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. public function countErrors(Request $request = null)
  65. {
  66. if (null !== $request) {
  67. return $this->errorCount[spl_object_hash($request)] ?? 0;
  68. }
  69. return array_sum($this->errorCount);
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function clear()
  75. {
  76. $this->records = [];
  77. $this->errorCount = [];
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function reset()
  83. {
  84. $this->clear();
  85. }
  86. }