diff --git a/README.md b/README.md index 169b11c..82265a3 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ Yii::setLogger( ->setPsrLogger(function () { // ... }) - ->withContext(function () { + ->withGlobalContext(function () { $context = []; // log remote IP address if available: diff --git a/src/Logger.php b/src/Logger.php index 0b93233..1e2a46a 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -5,6 +5,7 @@ use CLogger; use InvalidArgumentException; use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; use Yii; /** @@ -108,7 +109,7 @@ public function setPsrLogger($psrLogger): self * @param \Closure|array|null $globalLogContext global log context. * @return static self reference. */ - public function withContext($globalLogContext): self + public function withGlobalContext($globalLogContext): self { if ($globalLogContext !== null && !is_array($globalLogContext) && !$globalLogContext instanceof \Closure) { throw new InvalidArgumentException('"' . get_class($this) . '::$globalLogContext" should be either an array or a `\\Closure`'); @@ -205,6 +206,22 @@ protected function getGlobalLogContext(): array try { return call_user_func($this->_globalLogContext); } catch (\Throwable $exception) { + $errorMessage = 'Unable to resolve global log context: ' . $exception->getMessage(); + + if (($psrLogger = $this->getPsrLogger()) !== null) { + $psrLogger->log( + LogLevel::ERROR, + $errorMessage, + [ + 'exception' => $exception, + ] + ); + } + + if ($this->yiiLogEnabled) { + parent::log($errorMessage, CLogger::LEVEL_ERROR, 'system.log'); + } + return []; } } diff --git a/tests/LoggerTest.php b/tests/LoggerTest.php index 0874189..0484160 100644 --- a/tests/LoggerTest.php +++ b/tests/LoggerTest.php @@ -172,7 +172,7 @@ public function testGlobalLogContext(): void $logger = (new Logger()) ->setPsrLogger($psrLogger) - ->withContext(function () { + ->withGlobalContext(function () { return [ 'global' => 'global-context', ];