OpenXE/classes/Components/Logger/Logger.php

76 lines
2.1 KiB
PHP
Raw Normal View History

2021-05-21 08:49:41 +02:00
<?php
declare(strict_types=1);
namespace Xentral\Components\Logger;
use Xentral\Components\Logger\Context\ContextHelper;
use Xentral\Components\Logger\Exception\InvalidArgumentException;
use Xentral\Components\Logger\Handler\LogHandlerInterface;
final class Logger extends AbstractLogger
{
2024-06-28 15:48:39 +02:00
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
2021-05-21 08:49:41 +02:00
/** @var LogHandlerInterface[] $levelHandlers */
private $logHandlers;
/** @var ContextHelper $contextHelper */
private $contextHelper;
/**
* @param ContextHelper $contextHelper
*/
public function __construct(ContextHelper $contextHelper)
{
$this->contextHelper = $contextHelper;
$this->logHandlers = [];
}
/**
* @param LogHandlerInterface $handler
*
* @return void
*/
public function pushHandler(LogHandlerInterface $handler): void
{
$this->logHandlers[] = $handler;
}
/**
* @param string $level
* @param mixed $message
* @param array $context
*
* @throws InvalidArgumentException
*
* @return void
*/
public function log($level, $message, array $context = []): void
{
if (!in_array($level, self::LOGLEVELS, true)) {
throw new InvalidArgumentException(sprintf('Unrecognised loglevel "%s".', $level));
}
if (!is_string($message) && !method_exists($message, '__toString')) {
throw new InvalidArgumentException('Cannot convert Message to String.');
}
if (count($this->logHandlers) === 0) {
return;
}
$interpolated = $this->contextHelper->interpolateMessage($message, $context);
$contextObj = $this->contextHelper->createContext($context);
foreach ($this->logHandlers as $handler) {
if ($handler->canHandle($level)) {
$handler->addLogEntry($level, $interpolated, $contextObj);
}
}
}
}