MinMaxHandler.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Monolog\Handler;
  3. use Monolog\Logger;
  4. /**
  5. * Simple handler wrapper that processes only log entries, which are between the min and max log level.
  6. *
  7. * @author Hennadiy Verkh
  8. */
  9. class MinMaxHandler extends AbstractHandler
  10. {
  11. /**
  12. * Handler or factory callable($record, $this)
  13. *
  14. * @var callable|\Monolog\Handler\HandlerInterface
  15. */
  16. protected $handler;
  17. /**
  18. * Minimum level for logs that are passes to handler
  19. *
  20. * @var int
  21. */
  22. protected $minLevel;
  23. /**
  24. * Maximum level for logs that are passes to handler
  25. *
  26. * @var int
  27. */
  28. protected $maxLevel;
  29. /**
  30. * Whether the messages that are handled can bubble up the stack or not
  31. *
  32. * @var Boolean
  33. */
  34. protected $bubble;
  35. /**
  36. * @param callable|HandlerInterface $handler Handler or factory callable($record, $this).
  37. * @param int $minLevel Minimum level for logs that are passes to handler
  38. * @param int $maxLevel Maximum level for logs that are passes to handler
  39. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  40. */
  41. public function __construct($handler, $minLevel = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, $bubble = true)
  42. {
  43. $this->handler = $handler;
  44. $this->minLevel = $minLevel;
  45. $this->maxLevel = $maxLevel;
  46. $this->bubble = $bubble;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function isHandling(array $record)
  52. {
  53. return $record['level'] >= $this->minLevel && $record['level'] <= $this->maxLevel;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function handle(array $record)
  59. {
  60. if (!$this->isHandling($record)) {
  61. return false;
  62. }
  63. // The same logic as in FingersCrossedHandler
  64. if (!$this->handler instanceof HandlerInterface) {
  65. if (!is_callable($this->handler)) {
  66. throw new \RuntimeException(
  67. "The given handler (" . json_encode($this->handler)
  68. . ") is not a callable nor a Monolog\\Handler\\HandlerInterface object"
  69. );
  70. }
  71. $this->handler = call_user_func($this->handler, $record, $this);
  72. if (!$this->handler instanceof HandlerInterface) {
  73. throw new \RuntimeException("The factory callable should return a HandlerInterface");
  74. }
  75. }
  76. if ($this->processors) {
  77. foreach ($this->processors as $processor) {
  78. $record = call_user_func($processor, $record);
  79. }
  80. }
  81. $this->handler->handle($record);
  82. return false === $this->bubble;
  83. }
  84. }