Skip to content

Commit

Permalink
add logging of error on global context resolution
Browse files Browse the repository at this point in the history
  • Loading branch information
klimov-paul committed Jul 19, 2023
1 parent 8933903 commit 6ac2dc7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ Yii::setLogger(
->setPsrLogger(function () {
// ...
})
->withContext(function () {
->withGlobalContext(function () {
$context = [];

// log remote IP address if available:
Expand Down
19 changes: 18 additions & 1 deletion src/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use CLogger;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Yii;

/**
Expand Down Expand Up @@ -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`');
Expand Down Expand Up @@ -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 [];
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public function testGlobalLogContext(): void

$logger = (new Logger())
->setPsrLogger($psrLogger)
->withContext(function () {
->withGlobalContext(function () {
return [
'global' => 'global-context',
];
Expand Down

0 comments on commit 6ac2dc7

Please sign in to comment.