2022-10-17 21:25:03 +02:00
|
|
|
<?php declare(strict_types=1);
|
|
|
|
|
|
|
|
/*
|
|
|
|
* This file is part of the Monolog package.
|
|
|
|
*
|
|
|
|
* (c) Jordi Boggiano <j.boggiano@seld.be>
|
|
|
|
*
|
|
|
|
* For the full copyright and license information, please view the LICENSE
|
|
|
|
* file that was distributed with this source code.
|
|
|
|
*/
|
|
|
|
|
|
|
|
namespace Monolog\Handler;
|
|
|
|
|
|
|
|
use Monolog\Formatter\LineFormatter;
|
|
|
|
use Monolog\Formatter\FormatterInterface;
|
2023-07-02 23:57:24 +02:00
|
|
|
use Monolog\Logger;
|
2022-10-17 21:25:03 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Sends the message to a Redis Pub/Sub channel using PUBLISH
|
|
|
|
*
|
|
|
|
* usage example:
|
|
|
|
*
|
|
|
|
* $log = new Logger('application');
|
2023-07-02 23:57:24 +02:00
|
|
|
* $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Logger::WARNING);
|
2022-10-17 21:25:03 +02:00
|
|
|
* $log->pushHandler($redis);
|
|
|
|
*
|
|
|
|
* @author Gaëtan Faugère <gaetan@fauge.re>
|
|
|
|
*/
|
|
|
|
class RedisPubSubHandler extends AbstractProcessingHandler
|
|
|
|
{
|
2023-07-02 23:57:24 +02:00
|
|
|
/** @var \Predis\Client<\Predis\Client>|\Redis */
|
|
|
|
private $redisClient;
|
|
|
|
/** @var string */
|
|
|
|
private $channelKey;
|
2022-10-17 21:25:03 +02:00
|
|
|
|
|
|
|
/**
|
2023-07-02 23:57:24 +02:00
|
|
|
* @param \Predis\Client<\Predis\Client>|\Redis $redis The redis instance
|
|
|
|
* @param string $key The channel key to publish records to
|
2022-10-17 21:25:03 +02:00
|
|
|
*/
|
2023-07-02 23:57:24 +02:00
|
|
|
public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true)
|
2022-10-17 21:25:03 +02:00
|
|
|
{
|
2023-07-02 23:57:24 +02:00
|
|
|
if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
|
|
|
|
throw new \InvalidArgumentException('Predis\Client or Redis instance required');
|
|
|
|
}
|
|
|
|
|
2022-10-17 21:25:03 +02:00
|
|
|
$this->redisClient = $redis;
|
|
|
|
$this->channelKey = $key;
|
|
|
|
|
|
|
|
parent::__construct($level, $bubble);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-07-02 23:57:24 +02:00
|
|
|
* {@inheritDoc}
|
2022-10-17 21:25:03 +02:00
|
|
|
*/
|
2023-07-02 23:57:24 +02:00
|
|
|
protected function write(array $record): void
|
2022-10-17 21:25:03 +02:00
|
|
|
{
|
2023-07-02 23:57:24 +02:00
|
|
|
$this->redisClient->publish($this->channelKey, $record["formatted"]);
|
2022-10-17 21:25:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-07-02 23:57:24 +02:00
|
|
|
* {@inheritDoc}
|
2022-10-17 21:25:03 +02:00
|
|
|
*/
|
|
|
|
protected function getDefaultFormatter(): FormatterInterface
|
|
|
|
{
|
|
|
|
return new LineFormatter();
|
|
|
|
}
|
|
|
|
}
|