4 * This file is part of the Monolog package.
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Monolog\Handler;
15 use Monolog\Formatter\JsonFormatter;
16 use PhpAmqpLib\Message\AMQPMessage;
17 use PhpAmqpLib\Channel\AMQPChannel;
20 class AmqpHandler extends AbstractProcessingHandler
23 * @var AMQPExchange|AMQPChannel $exchange
30 protected $exchangeName;
33 * @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use
34 * @param string $exchangeName
36 * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
38 public function __construct($exchange, $exchangeName = 'log', $level = Logger::DEBUG, $bubble = true)
40 if ($exchange instanceof AMQPExchange) {
41 $exchange->setName($exchangeName);
42 } elseif ($exchange instanceof AMQPChannel) {
43 $this->exchangeName = $exchangeName;
45 throw new \InvalidArgumentException('PhpAmqpLib\Channel\AMQPChannel or AMQPExchange instance required');
47 $this->exchange = $exchange;
49 parent::__construct($level, $bubble);
55 protected function write(array $record)
57 $data = $record["formatted"];
58 $routingKey = $this->getRoutingKey($record);
60 if ($this->exchange instanceof AMQPExchange) {
61 $this->exchange->publish(
67 'content_type' => 'application/json',
71 $this->exchange->basic_publish(
72 $this->createAmqpMessage($data),
82 public function handleBatch(array $records)
84 if ($this->exchange instanceof AMQPExchange) {
85 parent::handleBatch($records);
90 foreach ($records as $record) {
91 if (!$this->isHandling($record)) {
95 $record = $this->processRecord($record);
96 $data = $this->getFormatter()->format($record);
98 $this->exchange->batch_basic_publish(
99 $this->createAmqpMessage($data),
101 $this->getRoutingKey($record)
105 $this->exchange->publish_batch();
109 * Gets the routing key for the AMQP exchange
111 * @param array $record
114 protected function getRoutingKey(array $record)
116 $routingKey = sprintf(
118 // TODO 2.0 remove substr call
119 substr($record['level_name'], 0, 4),
123 return strtolower($routingKey);
127 * @param string $data
128 * @return AMQPMessage
130 private function createAmqpMessage($data)
132 return new AMQPMessage(
135 'delivery_mode' => 2,
136 'content_type' => 'application/json',
144 protected function getDefaultFormatter()
146 return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);