GelfHandler.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 Gelf\IMessagePublisher;
  12. use Gelf\PublisherInterface;
  13. use Gelf\Publisher;
  14. use InvalidArgumentException;
  15. use Monolog\Logger;
  16. use Monolog\Formatter\GelfMessageFormatter;
  17. /**
  18. * Handler to send messages to a Graylog2 (http://www.graylog2.org) server
  19. *
  20. * @author Matt Lehner <mlehner@gmail.com>
  21. * @author Benjamin Zikarsky <benjamin@zikarsky.de>
  22. */
  23. class GelfHandler extends AbstractProcessingHandler
  24. {
  25. /**
  26. * @var Publisher the publisher object that sends the message to the server
  27. */
  28. protected $publisher;
  29. /**
  30. * @param PublisherInterface|IMessagePublisher|Publisher $publisher a publisher object
  31. * @param int $level The minimum logging level at which this handler will be triggered
  32. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  33. */
  34. public function __construct($publisher, $level = Logger::DEBUG, $bubble = true)
  35. {
  36. parent::__construct($level, $bubble);
  37. if (!$publisher instanceof Publisher && !$publisher instanceof IMessagePublisher && !$publisher instanceof PublisherInterface) {
  38. throw new InvalidArgumentException('Invalid publisher, expected a Gelf\Publisher, Gelf\IMessagePublisher or Gelf\PublisherInterface instance');
  39. }
  40. $this->publisher = $publisher;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function close()
  46. {
  47. $this->publisher = null;
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. protected function write(array $record)
  53. {
  54. $this->publisher->publish($record['formatted']);
  55. }
  56. /**
  57. * {@inheritDoc}
  58. */
  59. protected function getDefaultFormatter()
  60. {
  61. return new GelfMessageFormatter();
  62. }
  63. }