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;
17 * Buffers all records until closing the handler and then pass them as batch.
19 * This is useful for a MailHandler to send only one mail per request instead of
20 * sending one per log message.
22 * @author Christophe Coevoet <stof@notk.org>
24 class BufferHandler extends AbstractHandler
27 protected $bufferSize = 0;
28 protected $bufferLimit;
29 protected $flushOnOverflow;
30 protected $buffer = array();
31 protected $initialized = false;
34 * @param HandlerInterface $handler Handler.
35 * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
36 * @param int $level The minimum logging level at which this handler will be triggered
37 * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
38 * @param Boolean $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded
40 public function __construct(HandlerInterface $handler, $bufferLimit = 0, $level = Logger::DEBUG, $bubble = true, $flushOnOverflow = false)
42 parent::__construct($level, $bubble);
43 $this->handler = $handler;
44 $this->bufferLimit = (int) $bufferLimit;
45 $this->flushOnOverflow = $flushOnOverflow;
51 public function handle(array $record)
53 if ($record['level'] < $this->level) {
57 if (!$this->initialized) {
58 // __destructor() doesn't get called on Fatal errors
59 register_shutdown_function(array($this, 'close'));
60 $this->initialized = true;
63 if ($this->bufferLimit > 0 && $this->bufferSize === $this->bufferLimit) {
64 if ($this->flushOnOverflow) {
67 array_shift($this->buffer);
72 if ($this->processors) {
73 foreach ($this->processors as $processor) {
74 $record = call_user_func($processor, $record);
78 $this->buffer[] = $record;
81 return false === $this->bubble;
84 public function flush()
86 if ($this->bufferSize === 0) {
90 $this->handler->handleBatch($this->buffer);
94 public function __destruct()
96 // suppress the parent behavior since we already have register_shutdown_function()
97 // to call close(), and the reference contained there will prevent this from being
98 // GC'd until the end of the request
104 public function close()
110 * Clears the buffer without flushing any messages down to the wrapped handler.
112 public function clear()
114 $this->bufferSize = 0;
115 $this->buffer = array();