1<?php declare(strict_types=1);
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog\Handler;
13
14use Monolog\Formatter\LineFormatter;
15use Monolog\Formatter\FormatterInterface;
16use Monolog\Logger;
17
18/**
19 * Sends the message to a Redis Pub/Sub channel using PUBLISH
20 *
21 * usage example:
22 *
23 *   $log = new Logger('application');
24 *   $redis = new RedisPubSubHandler(new Predis\Client("tcp://localhost:6379"), "logs", Logger::WARNING);
25 *   $log->pushHandler($redis);
26 *
27 * @author Gaëtan Faugère <gaetan@fauge.re>
28 */
29class RedisPubSubHandler extends AbstractProcessingHandler
30{
31    /** @var \Predis\Client|\Redis */
32    private $redisClient;
33    /** @var string */
34    private $channelKey;
35
36    /**
37     * @param \Predis\Client|\Redis $redis The redis instance
38     * @param string                $key   The channel key to publish records to
39     */
40    public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true)
41    {
42        if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
43            throw new \InvalidArgumentException('Predis\Client or Redis instance required');
44        }
45
46        $this->redisClient = $redis;
47        $this->channelKey = $key;
48
49        parent::__construct($level, $bubble);
50    }
51
52    /**
53     * {@inheritDoc}
54     */
55    protected function write(array $record): void
56    {
57        $this->redisClient->publish($this->channelKey, $record["formatted"]);
58    }
59
60    /**
61     * {@inheritDoc}
62     */
63    protected function getDefaultFormatter(): FormatterInterface
64    {
65        return new LineFormatter();
66    }
67}
68