LoggerChannel.php in Drupal 9
File
core/lib/Drupal/Core/Logger/LoggerChannel.php
View source
<?php
namespace Drupal\Core\Logger;
use Drupal\Core\Session\AccountInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Psr\Log\LogLevel;
use Symfony\Component\HttpFoundation\RequestStack;
class LoggerChannel implements LoggerChannelInterface {
use LoggerTrait;
const MAX_CALL_DEPTH = 5;
protected $callDepth = 0;
protected $channel;
protected $levelTranslation = [
LogLevel::EMERGENCY => RfcLogLevel::EMERGENCY,
LogLevel::ALERT => RfcLogLevel::ALERT,
LogLevel::CRITICAL => RfcLogLevel::CRITICAL,
LogLevel::ERROR => RfcLogLevel::ERROR,
LogLevel::WARNING => RfcLogLevel::WARNING,
LogLevel::NOTICE => RfcLogLevel::NOTICE,
LogLevel::INFO => RfcLogLevel::INFO,
LogLevel::DEBUG => RfcLogLevel::DEBUG,
];
protected $loggers = [];
protected $requestStack;
protected $currentUser;
public function __construct($channel) {
$this->channel = $channel;
}
public function log($level, $message, array $context = []) {
if ($this->callDepth == self::MAX_CALL_DEPTH) {
return;
}
$this->callDepth++;
$context += [
'channel' => $this->channel,
'link' => '',
'uid' => 0,
'request_uri' => '',
'referer' => '',
'ip' => '',
'timestamp' => time(),
];
if ($this->requestStack && ($request = $this->requestStack
->getCurrentRequest())) {
$context['request_uri'] = $request
->getUri();
$context['referer'] = $request->headers
->get('Referer', '');
$context['ip'] = $request
->getClientIP();
if ($this->currentUser) {
$context['uid'] = $this->currentUser
->id();
}
}
if (is_string($level)) {
$level = $this->levelTranslation[$level];
}
foreach ($this
->sortLoggers() as $logger) {
$logger
->log($level, $message, $context);
}
$this->callDepth--;
}
public function setRequestStack(RequestStack $requestStack = NULL) {
$this->requestStack = $requestStack;
}
public function setCurrentUser(AccountInterface $current_user = NULL) {
$this->currentUser = $current_user;
}
public function setLoggers(array $loggers) {
$this->loggers = $loggers;
}
public function addLogger(LoggerInterface $logger, $priority = 0) {
$this->loggers[$priority][] = $logger;
}
protected function sortLoggers() {
$sorted = [];
krsort($this->loggers);
foreach ($this->loggers as $loggers) {
$sorted = array_merge($sorted, $loggers);
}
return $sorted;
}
}
Classes
Name |
Description |
LoggerChannel |
Defines a logger channel that most implementations will use. |