BufferHandler.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 = 0;
  24. protected $bufferLimit;
  25. protected $flushOnOverflow;
  26. protected $buffer = array();
  27. /**
  28. * @param HandlerInterface $handler Handler.
  29. * @param integer $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
  30. * @param integer $level The minimum logging level at which this handler will be triggered
  31. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  32. * @param Boolean $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded
  33. */
  34. public function __construct(HandlerInterface $handler, $bufferSize = 0, $level = Logger::DEBUG, $bubble = true, $flushOnOverflow = false)
  35. {
  36. parent::__construct($level, $bubble);
  37. $this->handler = $handler;
  38. $this->bufferLimit = (int) $bufferSize;
  39. $this->flushOnOverflow = $flushOnOverflow;
  40. // __destructor() doesn't get called on Fatal errors
  41. register_shutdown_function(array($this, 'close'));
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function handle(array $record)
  47. {
  48. if ($record['level'] < $this->level) {
  49. return false;
  50. }
  51. if ($this->bufferLimit > 0 && $this->bufferSize === $this->bufferLimit) {
  52. if ($this->flushOnOverflow) {
  53. $this->flush();
  54. } else {
  55. array_shift($this->buffer);
  56. $this->bufferSize--;
  57. }
  58. }
  59. $this->buffer[] = $record;
  60. $this->bufferSize++;
  61. return false === $this->bubble;
  62. }
  63. public function flush()
  64. {
  65. if ($this->bufferSize === 0) {
  66. return;
  67. }
  68. $this->handler->handleBatch($this->buffer);
  69. $this->bufferSize = 0;
  70. $this->buffer = array();
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function close()
  76. {
  77. $this->flush();
  78. }
  79. }