PsrHandler.php 2.3 KB

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