Stdout.php in log_stdout 8.2
File
src/Logger/Stdout.php
View source
<?php
namespace Drupal\log_stdout\Logger;
use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
class Stdout implements LoggerInterface {
use RfcLoggerTrait;
protected $config;
protected $parser;
public function __construct(ConfigFactoryInterface $config_factory, LogMessageParserInterface $parser) {
$this->config = $config_factory
->get('log_stdout.settings');
$this->parser = $parser;
}
public function log($level, $message, array $context = []) {
global $base_url;
if ($this->config
->get('use_stderr') == '1' && $level <= RfcLogLevel::WARNING) {
$output = fopen('php://stderr', 'w');
}
else {
$output = fopen('php://stdout', 'w');
}
$severity = strtoupper(RfcLogLevel::getLevels()[$level]);
$username = $this
->getUserName($context);
$variables = $this->parser
->parseMessagePlaceholders($message, $context);
$message = empty($variables) ? $message : strtr($message, $variables);
$fmt = $this->config
->get('format');
if (empty($fmt)) {
$fmt = '@date' . '|@timestamp' . '|@severity' . '|@type' . '|@message' . '|@uid' . '|@request_uri' . '|@referer' . '|@ip' . '|@link';
}
$entry = strtr($fmt, [
'@base_url' => $base_url,
'@timestamp' => $context['timestamp'],
'@severity' => $severity,
'@type' => $context['channel'],
'@message' => strip_tags($message),
'@uid' => $context['uid'],
'@request_uri' => $context['request_uri'],
'@referer' => $context['referer'],
'@ip' => $context['ip'],
'@link' => strip_tags($context['link']),
'@date' => date('Y-m-d\\TH:i:s', $context['timestamp']),
]);
fwrite($output, $entry . "\r\n");
fclose($output);
}
private function getUserName(array $context) {
if (isset($context['user']) && !empty($context['user'])) {
return $context['user']
->getAccountName();
}
return 'anonymous';
}
}