RollbarHandler.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  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 Monolog\Handler;
  11. use RollbarNotifier;
  12. use Exception;
  13. use Monolog\Logger;
  14. /**
  15. * Sends errors to Rollbar
  16. *
  17. * @author Paul Statezny <paulstatezny@gmail.com>
  18. */
  19. class RollbarHandler extends AbstractProcessingHandler
  20. {
  21. /**
  22. * Rollbar notifier
  23. *
  24. * @var RollbarNotifier
  25. */
  26. protected $rollbarNotifier;
  27. /**
  28. * Records whether any log records have been added since the last flush of the rollbar notifier
  29. *
  30. * @var bool
  31. */
  32. private $hasRecords = false;
  33. /**
  34. * @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token
  35. * @param int $level The minimum logging level at which this handler will be triggered
  36. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  37. */
  38. public function __construct(RollbarNotifier $rollbarNotifier, $level = Logger::ERROR, $bubble = true)
  39. {
  40. $this->rollbarNotifier = $rollbarNotifier;
  41. parent::__construct($level, $bubble);
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. protected function write(array $record)
  47. {
  48. if (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) {
  49. $context = $record['context'];
  50. $exception = $context['exception'];
  51. unset($context['exception']);
  52. $payload = array();
  53. if (isset($context['payload'])) {
  54. $payload = $context['payload'];
  55. unset($context['payload']);
  56. }
  57. $this->rollbarNotifier->report_exception($exception, $context, $payload);
  58. } else {
  59. $extraData = array(
  60. 'level' => $record['level'],
  61. 'channel' => $record['channel'],
  62. 'datetime' => $record['datetime']->format('U'),
  63. );
  64. $this->rollbarNotifier->report_message(
  65. $record['message'],
  66. $record['level_name'],
  67. array_merge($record['context'], $record['extra'], $extraData)
  68. );
  69. }
  70. $this->hasRecords = true;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function close()
  76. {
  77. if ($this->hasRecords) {
  78. $this->rollbarNotifier->flush();
  79. $this->hasRecords = false;
  80. }
  81. }
  82. }