Skip to content

Commit

Permalink
First run at migrating all the static calls to the Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
tvdijen committed Aug 28, 2021
1 parent 26375b5 commit 88a231b
Show file tree
Hide file tree
Showing 22 changed files with 296 additions and 123 deletions.
16 changes: 10 additions & 6 deletions lib/SimpleSAML/Auth/State.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ public static function saveState(array &$state, string $stage, bool $rawId = fal
$session = Session::getSessionFromRequest();
$session->setData('\SimpleSAML\Auth\State', $id, $serializedState, self::getStateTimeout());

Logger::debug('Saved state: ' . var_export($return, true));
$logger = new Logger();
$logger->debug('Saved state: ' . var_export($return, true));

return $return;
}
Expand All @@ -232,13 +233,14 @@ public static function cloneState(array $state): array
{
$clonedState = $state;

$logger = new Logger();
if (array_key_exists(self::ID, $state)) {
$clonedState[self::CLONE_ORIGINAL_ID] = $state[self::ID];
unset($clonedState[self::ID]);

Logger::debug('Cloned state: ' . var_export($state[self::ID], true));
$this->logger->debug('Cloned state: ' . var_export($state[self::ID], true));
} else {
Logger::debug('Cloned state with undefined id.');
$this->logger->debug('Cloned state with undefined id.');
}

return $clonedState;
Expand All @@ -263,7 +265,8 @@ public static function cloneState(array $state): array
*/
public static function loadState(string $id, string $stage, bool $allowMissing = false): ?array
{
Logger::debug('Loading state: ' . var_export($id, true));
$logger = new Logger();
$logger->debug('Loading state: ' . var_export($id, true));

$sid = self::parseStateID($id);

Expand Down Expand Up @@ -299,7 +302,7 @@ public static function loadState(string $id, string $stage, bool $allowMissing =
$msg = 'Wrong stage in state. Was \'' . $state[self::STAGE] .
'\', should be \'' . $stage . '\'.';

Logger::warning($msg);
$logger->warning($msg);

if ($sid['url'] === null) {
throw new \Exception($msg);
Expand All @@ -326,7 +329,8 @@ public static function deleteState(array &$state): void
return;
}

Logger::debug('Deleting state: ' . var_export($state[self::ID], true));
$logger = new Logger();
$logger->debug('Deleting state: ' . var_export($state[self::ID], true));

$session = Session::getSessionFromRequest();
$session->deleteData('\SimpleSAML\Auth\State', $state[self::ID]);
Expand Down
15 changes: 11 additions & 4 deletions lib/SimpleSAML/Error/Exception.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ class Exception extends \Exception
*/
private ?Exception $cause = null;

/**
* The Logger to use.
*
* @var \SimpleSAML\Logger
*/
private Logger $logger;


/**
* Constructor for this error.
Expand Down Expand Up @@ -245,7 +252,7 @@ public function log(string $default_level): void
*/
public function logError(): void
{
Logger::error($this->getClass() . ': ' . $this->getMessage());
$this->logger->error($this->getClass() . ': ' . $this->getMessage());
$this->logBacktrace(LogLevel::ERROR);
}

Expand All @@ -257,7 +264,7 @@ public function logError(): void
*/
public function logWarning(): void
{
Logger::warning($this->getClass() . ': ' . $this->getMessage());
$this->logger->warning($this->getClass() . ': ' . $this->getMessage());
$this->logBacktrace(LogLevel::WARNING);
}

Expand All @@ -269,7 +276,7 @@ public function logWarning(): void
*/
public function logInfo(): void
{
Logger::info($this->getClass() . ': ' . $this->getMessage());
$this->logger->info($this->getClass() . ': ' . $this->getMessage());
$this->logBacktrace(LogLevel::INFO);
}

Expand All @@ -281,7 +288,7 @@ public function logInfo(): void
*/
public function logDebug(): void
{
Logger::debug($this->getClass() . ': ' . $this->getMessage());
$this->logger->debug($this->getClass() . ': ' . $this->getMessage());
$this->logBacktrace(LogLevel::DEBUG);
}

Expand Down
12 changes: 10 additions & 2 deletions lib/SimpleSAML/Locale/Language.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,13 @@ class Language
'nn' => 'nn_NO',
];

/**
* The Logger to use
*
* @var \SimpleSAML\Logger
*/
private Logger $logger;


/**
* Constructor
Expand All @@ -145,6 +152,7 @@ class Language
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
$this->logger = new Logger();
$this->availableLanguages = $this->getInstalledLanguages();
$this->defaultLanguage = $this->configuration->getString('language.default', 'en');
$this->languageParameterName = $this->configuration->getString('language.parameter.name', 'language');
Expand Down Expand Up @@ -172,7 +180,7 @@ private function getInstalledLanguages(): array
if (array_key_exists($code, self::$language_names) && isset(self::$language_names[$code])) {
$availableLanguages[] = $code;
} else {
Logger::error("Language \"$code\" not installed. Check config.");
$this->logger->error("Language \"$code\" not installed. Check config.");
}
}
return $availableLanguages;
Expand Down Expand Up @@ -266,7 +274,7 @@ public function getLanguageLocalizedName(string $code): ?string
if (array_key_exists($code, self::$language_names) && isset(self::$language_names[$code])) {
return self::$language_names[$code];
}
Logger::error("Name for language \"$code\" not found. Check config.");
$this->logger->error("Name for language \"$code\" not found. Check config.");
return null;
}

Expand Down
24 changes: 16 additions & 8 deletions lib/SimpleSAML/Locale/Localization.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ class Localization
*/
public string $i18nBackend;

/**
* The Logger to use
*
* @var\SimpleSAML\Logger
*/
private Logger $logger;


/**
* Constructor
Expand All @@ -97,6 +104,7 @@ class Localization
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
$this->logger = new Logger();
/** @var string $locales */
$locales = $this->configuration->resolvePath('locales');
$this->localeDir = $locales;
Expand Down Expand Up @@ -160,7 +168,7 @@ public function addModuleDomain(string $module, string $localeDir = null): void
public function addDomain(string $localeDir, string $domain): void
{
$this->localeDomainMap[$domain] = $localeDir;
Logger::debug("Localization: load domain '$domain' at '$localeDir'");
$this->logger->debug("Localization: load domain '$domain' at '$localeDir'");
$this->loadGettextGettextFromPO($domain);
}

Expand All @@ -179,7 +187,7 @@ public function getLangPath(string $domain = self::DEFAULT_DOMAIN): string
$langcode = $langcode[0];
$localeDir = $this->localeDomainMap[$domain];
$langPath = $localeDir . '/' . $langcode . '/LC_MESSAGES/';
Logger::debug("Trying langpath for '$langcode' as '$langPath'");
$this->logger->debug("Trying langpath for '$langcode' as '$langPath'");
if (is_dir($langPath) && is_readable($langPath)) {
return $langPath;
}
Expand All @@ -188,7 +196,7 @@ public function getLangPath(string $domain = self::DEFAULT_DOMAIN): string
$alias = $this->language->getLanguageCodeAlias($langcode);
if (isset($alias)) {
$langPath = $localeDir . '/' . $alias . '/LC_MESSAGES/';
Logger::debug("Trying langpath for alternative '$alias' as '$langPath'");
$this->logger->debug("Trying langpath for alternative '$alias' as '$langPath'");
if (is_dir($langPath) && is_readable($langPath)) {
return $langPath;
}
Expand All @@ -201,13 +209,13 @@ public function getLangPath(string $domain = self::DEFAULT_DOMAIN): string
// Report that the localization for the preferred language is missing
$error = "Localization not found for langcode '$langcode' at '$langPath', falling back to langcode '" .
$defLangcode . "'";
Logger::error($_SERVER['PHP_SELF'] . ' - ' . $error);
$this->logger->error($_SERVER['PHP_SELF'] . ' - ' . $error);
return $langPath;
}

// Locale for default language missing even, error out
$error = "Localization directory missing/broken for langcode '$langcode' and domain '$domain'";
Logger::critical($_SERVER['PHP_SELF'] . ' - ' . $error);
$this->logger->critical($_SERVER['PHP_SELF'] . ' - ' . $error);
throw new \Exception($error);
}

Expand Down Expand Up @@ -241,7 +249,7 @@ private function loadGettextGettextFromPO(
$langPath = $this->getLangPath($domain);
} catch (\Exception $e) {
$error = "Something went wrong when trying to get path to language file, cannot load domain '$domain'.";
Logger::debug($_SERVER['PHP_SELF'] . ' - ' . $error);
$this->logger->debug($_SERVER['PHP_SELF'] . ' - ' . $error);
if ($catchException) {
// bail out!
return;
Expand All @@ -256,7 +264,7 @@ private function loadGettextGettextFromPO(
$this->translator->loadTranslations($translations);
} else {
$error = "Localization file '$poFile' not found in '$langPath', falling back to default";
Logger::debug($_SERVER['PHP_SELF'] . ' - ' . $error);
$this->logger->debug($_SERVER['PHP_SELF'] . ' - ' . $error);
}
}

Expand All @@ -283,7 +291,7 @@ public function isI18NBackendDefault(): bool
private function setupL10N(): void
{
if ($this->i18nBackend === self::SSP_I18N_BACKEND) {
Logger::debug("Localization: using old system");
$this->logger->debug("Localization: using old system");
return;
}

Expand Down
18 changes: 13 additions & 5 deletions lib/SimpleSAML/Locale/Translate.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ class Translate
*/
private Language $language;

/**
* The Logger to use
*
* @var \SimpleSAML\Logger
*/
private Logger $logger;


/**
* Constructor
Expand All @@ -65,6 +72,7 @@ public function __construct(Configuration $configuration, ?string $defaultDictio
$this->configuration = $configuration;
$this->language = new Language($configuration);
$this->defaultDictionary = $defaultDictionary;
$this->logger = new Logger();
}


Expand Down Expand Up @@ -209,7 +217,7 @@ public function includeInlineTranslation(string $tag, $translation): void
);
}

Logger::debug('Translate: Adding inline language translation for tag [' . $tag . ']');
$this->logger->debug('Translate: Adding inline language translation for tag [' . $tag . ']');
$this->langtext[$tag] = $translation;
}

Expand All @@ -233,7 +241,7 @@ public function includeLanguageFile(string $file, Configuration $otherConfig = n
$filebase = $filebase ?: 'dictionaries/';

$lang = $this->readDictionaryFile($filebase . $file);
Logger::debug('Translate: Merging language array. Loading [' . $file . ']');
$this->logger->debug('Translate: Merging language array. Loading [' . $file . ']');
$this->langtext = array_merge($this->langtext, $lang);
}

Expand All @@ -254,7 +262,7 @@ private function readDictionaryJSON(string $filename): array
$lang = json_decode($fileContent, true);

if (empty($lang)) {
Logger::error('Invalid dictionary definition file [' . $definitionFile . ']');
$this->logger->error('Invalid dictionary definition file [' . $definitionFile . ']');
return [];
}

Expand Down Expand Up @@ -303,7 +311,7 @@ private function readDictionaryPHP(string $filename): array
*/
private function readDictionaryFile(string $filename): array
{
Logger::debug('Translate: Reading dictionary [' . $filename . ']');
$this->logger->debug('Translate: Reading dictionary [' . $filename . ']');

$jsonFile = $filename . '.definition.json';
if (file_exists($jsonFile)) {
Expand All @@ -315,7 +323,7 @@ private function readDictionaryFile(string $filename): array
return $this->readDictionaryPHP($filename);
}

Logger::error(
$this->logger->error(
$_SERVER['PHP_SELF'] . ' - Translate: Could not find dictionary file at [' . $filename . ']'
);
return [];
Expand Down
23 changes: 12 additions & 11 deletions lib/SimpleSAML/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,12 @@ class Logger extends AbstractLogger
/**
* Statistics.
*
* @param string|\Stringable $message
* @param string $message
* @param array $context
*
* @return void
*/
public function stats(string|\Stringable $message, array $context = []): void
public function stats($message, array $context = []): void
{
$context['statsLog'] = true;
$this->log(LogLevel::EMERGENCY, $message, $context);
Expand Down Expand Up @@ -196,7 +196,7 @@ public static function setTrackId(string $trackId): void
public static function flush(): void
{
foreach (self::$earlyLog as $msg) {
$this->:log($msg['level'], $msg['string'], $msg['statsLog']);
$this->log($msg['level'], $msg['string'], $msg['statsLog']);
}
self::$earlyLog = [];
}
Expand Down Expand Up @@ -384,12 +384,13 @@ private static function createLoggingHandler(?string $handler = null): void
/**
* System is unusable.
*
* @param string|\Stringable $message
* @param string $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log(string|\Stringable $message, array $context = []): void
public function log($level, $message, array $context = []): void
{
$statsLog = false;
if (array_key_exists('statsLog', $context)) {
Expand All @@ -398,7 +399,7 @@ public function log(string|\Stringable $message, array $context = []): void

if (self::$initializing) {
// some error occurred while initializing logging
self::defer($level, $string, $statsLog);
self::defer($level, $message, $statsLog);
return;
} elseif (php_sapi_name() === 'cli' || defined('STDIN')) {
$_SERVER['REMOTE_ADDR'] = "CLI";
Expand All @@ -420,12 +421,12 @@ public function log(string|\Stringable $message, array $context = []): void
$usec = substr($msecs, 2, 3);

$ts = gmdate('H:i:s', $time) . '.' . $usec . 'Z';
self::$capturedLog[] = $ts . ' ' . $string;
self::$capturedLog[] = $ts . ' ' . $message;
}

if (self::$logLevel >= $level || $statsLog) {
$formats = ['%trackid', '%msg', '%srcip', '%stat'];
$replacements = [self::$trackid, $string, $_SERVER['REMOTE_ADDR']];
$replacements = [self::$trackid, $message, $_SERVER['REMOTE_ADDR']];

$stat = '';
if ($statsLog) {
Expand All @@ -435,7 +436,7 @@ public function log(string|\Stringable $message, array $context = []): void

if (self::$trackid === self::NO_TRACKID && !self::$shuttingDown) {
// we have a log without track ID and we are not still shutting down, so defer logging
self::defer($level, $string, $statsLog);
self::defer($level, $message, $statsLog);
return;
} elseif (self::$trackid === self::NO_TRACKID) {
// shutting down without a track ID, prettify it
Expand All @@ -444,8 +445,8 @@ public function log(string|\Stringable $message, array $context = []): void
}

// we either have a track ID or we are shutting down, so just log the message
$string = str_replace($formats, $replacements, self::$format);
self::$loggingHandler->log($level, $string);
$message = str_replace($formats, $replacements, self::$format);
self::$loggingHandler->log($level, $message);
}
}
}
Loading

0 comments on commit 88a231b

Please sign in to comment.