AmqpHandler.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 Monolog\Logger;
  12. use Monolog\Formatter\JsonFormatter;
  13. class AmqpHandler extends AbstractProcessingHandler
  14. {
  15. /**
  16. * @var \AMQPExchange $exchange
  17. */
  18. protected $exchange;
  19. /**
  20. * @param \AMQPExchange $exchange AMQP exchange, ready for use
  21. * @param string $exchangeName
  22. * @param int $level
  23. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  24. */
  25. public function __construct(\AMQPExchange $exchange, $exchangeName = 'log', $level = Logger::DEBUG, $bubble = true)
  26. {
  27. $this->exchange = $exchange;
  28. $this->exchange->setName($exchangeName);
  29. parent::__construct($level, $bubble);
  30. }
  31. /**
  32. * {@inheritDoc}
  33. */
  34. protected function write(array $record)
  35. {
  36. $data = $record["formatted"];
  37. $routingKey = sprintf(
  38. '%s.%s',
  39. substr($record['level_name'], 0, 4),
  40. $record['channel']
  41. );
  42. $this->exchange->publish(
  43. $data,
  44. strtolower($routingKey),
  45. 0,
  46. array(
  47. 'delivery_mode' => 2,
  48. 'Content-type' => 'application/json'
  49. )
  50. );
  51. }
  52. /**
  53. * {@inheritDoc}
  54. */
  55. protected function getDefaultFormatter()
  56. {
  57. return new JsonFormatter();
  58. }
  59. }