Skip to content

Commit

Permalink
Include extra in context in PsrHandler (#1852)
Browse files Browse the repository at this point in the history
  • Loading branch information
snapshotpl committed Apr 12, 2024
1 parent 000fedb commit 35dab43
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/Monolog/Handler/PsrHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,17 @@ class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
protected LoggerInterface $logger;

protected FormatterInterface|null $formatter = null;
private bool $includeExtra;

/**
* @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied
*/
public function __construct(LoggerInterface $logger, int|string|Level $level = Level::Debug, bool $bubble = true)
public function __construct(LoggerInterface $logger, int|string|Level $level = Level::Debug, bool $bubble = true, bool $includeExtra = false)
{
parent::__construct($level, $bubble);

$this->logger = $logger;
$this->includeExtra = $includeExtra;
}

/**
Expand All @@ -53,12 +55,15 @@ public function handle(LogRecord $record): bool
return false;
}

if ($this->formatter !== null) {
$formatted = $this->formatter->format($record);
$this->logger->log($record->level->toPsrLogLevel(), (string) $formatted, $record->context);
} else {
$this->logger->log($record->level->toPsrLogLevel(), $record->message, $record->context);
}
$message = $this->formatter !== null
? (string) $this->formatter->format($record)
: $record->message;

$context = $this->includeExtra
? [...$record->extra, ...$record->context]
: $record->context;

$this->logger->log($record->level->toPsrLogLevel(), $message, $context);

return false === $this->bubble;
}
Expand Down
16 changes: 16 additions & 0 deletions tests/Monolog/Handler/PsrHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,20 @@ public function testFormatter()
$handler->setFormatter(new LineFormatter('dummy'));
$handler->handle($this->getRecord($level, $message, context: $context, datetime: new \DateTimeImmutable()));
}

public function testIncludeExtra()
{
$message = 'Hello, world!';
$context = ['foo' => 'bar'];
$extra = ['baz' => 'boo'];
$level = Level::Error;

$psrLogger = $this->createMock('Psr\Log\NullLogger');
$psrLogger->expects($this->once())
->method('log')
->with($level->toPsrLogLevel(), $message, ['baz' => 'boo', 'foo' => 'bar']);

$handler = new PsrHandler($psrLogger, includeExtra: true);
$handler->handle($this->getRecord($level, $message, context: $context, datetime: new \DateTimeImmutable(), extra: $extra));
}
}

0 comments on commit 35dab43

Please sign in to comment.