BufferHandler.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Monolog\Logger;
  12. /**
  13. * Buffers all records until closing the handler and then pass them as batch.
  14. *
  15. * This is useful for a MailHandler to send only one mail per request instead of
  16. * sending one per log message.
  17. *
  18. * @author Christophe Coevoet <stof@notk.org>
  19. */
  20. class BufferHandler extends AbstractHandler
  21. {
  22. protected $handler;
  23. protected $bufferSize;
  24. protected $buffer = array();
  25. /**
  26. * @param HandlerInterface $handler Handler.
  27. * @param integer $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
  28. * @param integer $level The minimum logging level at which this handler will be triggered
  29. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  30. */
  31. public function __construct(HandlerInterface $handler, $bufferSize = 0, $level = Logger::DEBUG, $bubble = true)
  32. {
  33. parent::__construct($level, $bubble);
  34. $this->handler = $handler;
  35. $this->bufferSize = $bufferSize;
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function handle(array $record)
  41. {
  42. if ($record['level'] < $this->level) {
  43. return false;
  44. }
  45. $this->buffer[] = $record;
  46. if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) {
  47. array_shift($this->buffer);
  48. }
  49. return false === $this->bubble;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function close()
  55. {
  56. $this->handler->handleBatch($this->buffer);
  57. }
  58. }