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;
14 use Monolog\Formatter\LineFormatter;
18 * Logs to a Redis key using rpush
22 * $log = new Logger('application');
23 * $redis = new RedisHandler(new Predis\Client("tcp://localhost:6379"), "logs", "prod");
24 * $log->pushHandler($redis);
26 * @author Thomas Tourlourat <thomas@tourlourat.com>
28 class RedisHandler extends AbstractProcessingHandler
35 * @param \Predis\Client|\Redis $redis The redis instance
36 * @param string $key The key name to push records to
37 * @param int $level The minimum logging level at which this handler will be triggered
38 * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
39 * @param int $capSize Number of entries to limit list size to
41 public function __construct($redis, $key, $level = Logger::DEBUG, $bubble = true, $capSize = false)
43 if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
44 throw new \InvalidArgumentException('Predis\Client or Redis instance required');
47 $this->redisClient = $redis;
48 $this->redisKey = $key;
49 $this->capSize = $capSize;
51 parent::__construct($level, $bubble);
57 protected function write(array $record)
60 $this->writeCapped($record);
62 $this->redisClient->rpush($this->redisKey, $record["formatted"]);
67 * Write and cap the collection
68 * Writes the record to the redis list and caps its
70 * @param array $record associative record array
73 protected function writeCapped(array $record)
75 if ($this->redisClient instanceof \Redis) {
76 $this->redisClient->multi()
77 ->rpush($this->redisKey, $record["formatted"])
78 ->ltrim($this->redisKey, -$this->capSize, -1)
81 $redisKey = $this->redisKey;
82 $capSize = $this->capSize;
83 $this->redisClient->transaction(function ($tx) use ($record, $redisKey, $capSize) {
84 $tx->rpush($redisKey, $record["formatted"]);
85 $tx->ltrim($redisKey, -$capSize, -1);
93 protected function getDefaultFormatter()
95 return new LineFormatter();