NotifierHandler.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\Handler;
  11. use Monolog\Handler\AbstractHandler;
  12. use Monolog\Logger;
  13. use Symfony\Component\Notifier\Notification\Notification;
  14. use Symfony\Component\Notifier\Notifier;
  15. use Symfony\Component\Notifier\NotifierInterface;
  16. /**
  17. * Uses Notifier as a log handler.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class NotifierHandler extends AbstractHandler
  22. {
  23. private $notifier;
  24. /**
  25. * @param string|int $level The minimum logging level at which this handler will be triggered
  26. */
  27. public function __construct(NotifierInterface $notifier, $level = Logger::ERROR, bool $bubble = true)
  28. {
  29. $this->notifier = $notifier;
  30. parent::__construct(Logger::toMonologLevel($level) < Logger::ERROR ? Logger::ERROR : $level, $bubble);
  31. }
  32. public function handle(array $record): bool
  33. {
  34. if (!$this->isHandling($record)) {
  35. return false;
  36. }
  37. $this->notify([$record]);
  38. return !$this->bubble;
  39. }
  40. public function handleBatch(array $records): void
  41. {
  42. if ($records = array_filter($records, [$this, 'isHandling'])) {
  43. $this->notify($records);
  44. }
  45. }
  46. private function notify(array $records): void
  47. {
  48. $record = $this->getHighestRecord($records);
  49. if (($record['context']['exception'] ?? null) instanceof \Throwable) {
  50. $notification = Notification::fromThrowable($record['context']['exception']);
  51. } else {
  52. $notification = new Notification($record['message']);
  53. }
  54. $notification->importanceFromLogLevelName(Logger::getLevelName($record['level']));
  55. $this->notifier->send($notification, ...$this->notifier->getAdminRecipients());
  56. }
  57. private function getHighestRecord(array $records)
  58. {
  59. $highestRecord = null;
  60. foreach ($records as $record) {
  61. if (null === $highestRecord || $highestRecord['level'] < $record['level']) {
  62. $highestRecord = $record;
  63. }
  64. }
  65. return $highestRecord;
  66. }
  67. }