BufferHandler.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // __destructor() doesn't get called on Fatal errors
  37. register_shutdown_function(array($this, 'close'));
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function handle(array $record)
  43. {
  44. if ($record['level'] < $this->level) {
  45. return false;
  46. }
  47. $this->buffer[] = $record;
  48. if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) {
  49. array_shift($this->buffer);
  50. }
  51. return false === $this->bubble;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function close()
  57. {
  58. if ($this->buffer) {
  59. $this->handler->handleBatch($this->buffer);
  60. $this->buffer = array();
  61. }
  62. }
  63. }