AmqpHandler.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. * Describes current issuer (e.g. "database", "landing", "server" and so on)
  21. * @var string $issuer
  22. */
  23. protected $issuer;
  24. /**
  25. * @param \AMQPExchange $exchange AMQP exchange, ready for use
  26. * @param string $exchangeName
  27. * @param string $issuer isser name
  28. * @param int $level
  29. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  30. */
  31. public function __construct($exchange, $exchangeName = 'log', $issuer = 'default', $level = Logger::DEBUG, $bubble = true)
  32. {
  33. if (!$exchange instanceof \AMQPExchange) {
  34. throw new \LogicException('AMQP handler requires a valid exchange to be provided');
  35. }
  36. $this->exchange = $exchange;
  37. $this->exchange->setName($exchangeName);
  38. parent::__construct($level, $bubble);
  39. }
  40. /**
  41. * Writes the record down to the log of the implementing handler
  42. *
  43. * @param array $record
  44. * @return void
  45. */
  46. protected function write(array $record)
  47. {
  48. $data = $record["formatted"];
  49. $routingKey = sprintf('%s.%s',
  50. substr($record['level_name'], 0, 4),
  51. $this->getIssuer());
  52. //we do not check return value because no handler really does
  53. $this->exchange->publish($data,
  54. strtolower($routingKey),
  55. 0,
  56. array(
  57. 'delivery_mode' => 2,
  58. 'Content-type' => 'application/json'
  59. ));
  60. }
  61. /**
  62. * {@inheritDoc}
  63. */
  64. protected function getDefaultFormatter()
  65. {
  66. return new JsonFormatter();
  67. }
  68. /**
  69. * Issuer setter
  70. * @param string $issuer
  71. */
  72. public function setIssuer($issuer)
  73. {
  74. $this->issuer = $issuer;
  75. }
  76. /**
  77. * Issuer getter
  78. * @return string
  79. */
  80. public function getIssuer()
  81. {
  82. return $this->issuer;
  83. }
  84. }