scratch – Blame information for rev 115

Subversion Repositories:
Rev:
Rev Author Line No. Line
115 office 1 <?php
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  
12 namespace Monolog\Handler;
13  
14 use Monolog\Formatter\LineFormatter;
15 use Monolog\Logger;
16  
17 /**
18 * Logs to a Redis key using rpush
19 *
20 * usage example:
21 *
22 * $log = new Logger('application');
23 * $redis = new RedisHandler(new Predis\Client("tcp://localhost:6379"), "logs", "prod");
24 * $log->pushHandler($redis);
25 *
26 * @author Thomas Tourlourat <thomas@tourlourat.com>
27 */
28 class RedisHandler extends AbstractProcessingHandler
29 {
30 private $redisClient;
31 private $redisKey;
32 protected $capSize;
33  
34 /**
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
40 */
41 public function __construct($redis, $key, $level = Logger::DEBUG, $bubble = true, $capSize = false)
42 {
43 if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
44 throw new \InvalidArgumentException('Predis\Client or Redis instance required');
45 }
46  
47 $this->redisClient = $redis;
48 $this->redisKey = $key;
49 $this->capSize = $capSize;
50  
51 parent::__construct($level, $bubble);
52 }
53  
54 /**
55 * {@inheritDoc}
56 */
57 protected function write(array $record)
58 {
59 if ($this->capSize) {
60 $this->writeCapped($record);
61 } else {
62 $this->redisClient->rpush($this->redisKey, $record["formatted"]);
63 }
64 }
65  
66 /**
67 * Write and cap the collection
68 * Writes the record to the redis list and caps its
69 *
70 * @param array $record associative record array
71 * @return void
72 */
73 protected function writeCapped(array $record)
74 {
75 if ($this->redisClient instanceof \Redis) {
76 $this->redisClient->multi()
77 ->rpush($this->redisKey, $record["formatted"])
78 ->ltrim($this->redisKey, -$this->capSize, -1)
79 ->exec();
80 } else {
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);
86 });
87 }
88 }
89  
90 /**
91 * {@inheritDoc}
92 */
93 protected function getDefaultFormatter()
94 {
95 return new LineFormatter();
96 }
97 }