Skip to content

Instantly share code, notes, and snippets.

@Darkflib
Last active January 6, 2016 20:34
Show Gist options
  • Save Darkflib/fc30791018a41aecbd7f to your computer and use it in GitHub Desktop.
Save Darkflib/fc30791018a41aecbd7f to your computer and use it in GitHub Desktop.
<?php
/*
* This file an extension for the Monolog package that implements an AMQP handler based on
* the amqp library at https://github.com/videlalvaro/php-amqplib
*
* (c) Mike Preston <mike@technomonk.com>
*
*/
namespace Monolog\Handler;
use Monolog\Logger;
use Monolog\Formatter\JsonFormatter;
use PhpAmqpLib\Connection\AMQPConnection;
use PhpAmqpLib\Message\AMQPMessage;
class MikesAmqpHandler extends AbstractProcessingHandler
{
/**
* @var string $exchange
*/
protected $exchange;
protected $conn;
protected $ch;
/**
* @param array $amqpCred AMQP credentials
* @param string $exchangeName
* @param int $level
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct($amqpCred, $exchangeName = 'log', $level = Logger::DEBUG, $bubble = true)
{
$conn = new AMQPConnection($amqpCred['host'], $amqpCred['port'], $amqpCred['user'], $amqpCred['pass'], $amqpCred['vhost']);
if (!$conn) die('Error connecting to AMQP');
$ch = $conn->channel();
if (!$ch) die('Error connecting to AMQP');
$this->exchange = $exchange;
parent::__construct($level, $bubble);
}
/**
* {@inheritDoc}
*/
protected function write(array $record)
{
$data = $record["formatted"];
$routingKey = sprintf(
'%s.%s',
substr($record['level_name'], 0, 4),
$record['channel']
);
$msg_body=json_encode(array('body' => $msg, 'to' => $to, 'from' => $from, 'subject' => $subject , 'created' => microtime(TRUE)));
$msg = new AMQPMessage($msg_body, array('content_type' => 'application/json', 'delivery_mode' => 2));
$ch->basic_publish($msg, $this->exchange, strtolower($routingKey));
}
/**
* {@inheritDoc}
*/
protected function getDefaultFormatter()
{
return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment