friendica-addons/monolog/vendor/monolog/monolog/src/Monolog/Handler/PsrHandler.php

96 lines
2.4 KiB
PHP
Raw Normal View History

2022-10-17 21:25:03 +02:00
<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
2023-01-18 00:17:49 +01:00
use Monolog\Logger;
2022-10-17 21:25:03 +02:00
use Psr\Log\LoggerInterface;
use Monolog\Formatter\FormatterInterface;
/**
* Proxies log messages to an existing PSR-3 compliant logger.
*
* If a formatter is configured, the formatter's output MUST be a string and the
* formatted message will be fed to the wrapped PSR logger instead of the original
* log record's message.
*
* @author Michael Moussa <michael.moussa@gmail.com>
*/
class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
{
/**
* PSR-3 compliant logger
2023-01-18 00:17:49 +01:00
*
* @var LoggerInterface
2022-10-17 21:25:03 +02:00
*/
2023-01-18 00:17:49 +01:00
protected $logger;
2022-10-17 21:25:03 +02:00
2023-01-18 00:17:49 +01:00
/**
* @var FormatterInterface|null
*/
protected $formatter;
2022-10-17 21:25:03 +02:00
/**
* @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied
*/
2023-01-18 00:17:49 +01:00
public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true)
2022-10-17 21:25:03 +02:00
{
parent::__construct($level, $bubble);
$this->logger = $logger;
}
/**
2023-01-18 00:17:49 +01:00
* {@inheritDoc}
2022-10-17 21:25:03 +02:00
*/
2023-01-18 00:17:49 +01:00
public function handle(array $record): bool
2022-10-17 21:25:03 +02:00
{
if (!$this->isHandling($record)) {
return false;
}
2023-01-18 00:17:49 +01:00
if ($this->formatter) {
2022-10-17 21:25:03 +02:00
$formatted = $this->formatter->format($record);
2023-01-18 00:17:49 +01:00
$this->logger->log(strtolower($record['level_name']), (string) $formatted, $record['context']);
2022-10-17 21:25:03 +02:00
} else {
2023-01-18 00:17:49 +01:00
$this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']);
2022-10-17 21:25:03 +02:00
}
return false === $this->bubble;
}
/**
* Sets the formatter.
2023-01-18 00:17:49 +01:00
*
* @param FormatterInterface $formatter
2022-10-17 21:25:03 +02:00
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
$this->formatter = $formatter;
return $this;
}
/**
* Gets the formatter.
2023-01-18 00:17:49 +01:00
*
* @return FormatterInterface
2022-10-17 21:25:03 +02:00
*/
public function getFormatter(): FormatterInterface
{
2023-01-18 00:17:49 +01:00
if (!$this->formatter) {
2022-10-17 21:25:03 +02:00
throw new \LogicException('No formatter has been set and this handler does not have a default formatter');
}
return $this->formatter;
}
}