PsrHandler.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php declare(strict_types=1);
  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. use Psr\Log\LoggerInterface;
  13. use Monolog\Formatter\FormatterInterface;
  14. /**
  15. * Proxies log messages to an existing PSR-3 compliant logger.
  16. *
  17. * If a formatter is configured, the formatter's output MUST be a string and the
  18. * formatted message will be fed to the wrapped PSR logger instead of the original
  19. * log record's message.
  20. *
  21. * @author Michael Moussa <michael.moussa@gmail.com>
  22. */
  23. class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
  24. {
  25. /**
  26. * PSR-3 compliant logger
  27. *
  28. * @var LoggerInterface
  29. */
  30. protected $logger;
  31. /**
  32. * @var FormatterInterface|null
  33. */
  34. protected $formatter;
  35. /**
  36. * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied
  37. * @param string|int $level The minimum logging level at which this handler will be triggered
  38. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  39. */
  40. public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true)
  41. {
  42. parent::__construct($level, $bubble);
  43. $this->logger = $logger;
  44. }
  45. /**
  46. * {@inheritDoc}
  47. */
  48. public function handle(array $record): bool
  49. {
  50. if (!$this->isHandling($record)) {
  51. return false;
  52. }
  53. if ($this->formatter) {
  54. $formatted = $this->formatter->format($record);
  55. $this->logger->log(strtolower($record['level_name']), (string) $formatted, $record['context']);
  56. } else {
  57. $this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']);
  58. }
  59. return false === $this->bubble;
  60. }
  61. /**
  62. * Sets the formatter.
  63. *
  64. * @param FormatterInterface $formatter
  65. */
  66. public function setFormatter(FormatterInterface $formatter): HandlerInterface
  67. {
  68. $this->formatter = $formatter;
  69. return $this;
  70. }
  71. /**
  72. * Gets the formatter.
  73. *
  74. * @return FormatterInterface
  75. */
  76. public function getFormatter(): FormatterInterface
  77. {
  78. if (!$this->formatter) {
  79. throw new \LogicException('No formatter has been set and this handler does not have a default formatter');
  80. }
  81. return $this->formatter;
  82. }
  83. }