Keine Beschreibung

SamplingHandler.php 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. /**
  12. * Sampling handler
  13. *
  14. * A sampled event stream can be useful for logging high frequency events in
  15. * a production environment where you only need an idea of what is happening
  16. * and are not concerned with capturing every occurrence. Since the decision to
  17. * handle or not handle a particular event is determined randomly, the
  18. * resulting sampled log is not guaranteed to contain 1/N of the events that
  19. * occurred in the application, but based on the Law of large numbers, it will
  20. * tend to be close to this ratio with a large number of attempts.
  21. *
  22. * @author Bryan Davis <bd808@wikimedia.org>
  23. * @author Kunal Mehta <legoktm@gmail.com>
  24. */
  25. class SamplingHandler extends AbstractHandler
  26. {
  27. /**
  28. * @var callable|HandlerInterface $handler
  29. */
  30. protected $handler;
  31. /**
  32. * @var int $factor
  33. */
  34. protected $factor;
  35. /**
  36. * @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler).
  37. * @param int $factor Sample factor
  38. */
  39. public function __construct($handler, $factor)
  40. {
  41. parent::__construct();
  42. $this->handler = $handler;
  43. $this->factor = $factor;
  44. if (!$this->handler instanceof HandlerInterface && !is_callable($this->handler)) {
  45. throw new \RuntimeException("The given handler (".json_encode($this->handler).") is not a callable nor a Monolog\Handler\HandlerInterface object");
  46. }
  47. }
  48. public function isHandling(array $record)
  49. {
  50. return $this->handler->isHandling($record);
  51. }
  52. public function handle(array $record)
  53. {
  54. if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) {
  55. // The same logic as in FingersCrossedHandler
  56. if (!$this->handler instanceof HandlerInterface) {
  57. $this->handler = call_user_func($this->handler, $record, $this);
  58. if (!$this->handler instanceof HandlerInterface) {
  59. throw new \RuntimeException("The factory callable should return a HandlerInterface");
  60. }
  61. }
  62. if ($this->processors) {
  63. foreach ($this->processors as $processor) {
  64. $record = call_user_func($processor, $record);
  65. }
  66. }
  67. $this->handler->handle($record);
  68. }
  69. return false === $this->bubble;
  70. }
  71. }